dimanche 31 juillet 2016

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



via Chebli Mohamed

Laravel 5.1 - Why unit testing authentication fails with a model factory?

So using the factory method the 1st and 3rd test fail.

<?php

class AuthTest extends TestCase
{
     public function setUp()
     {
         parent::setUp();

         $this->artisan('migrate');
         //$this->artisan('db:seed');
         $user = factory(RMS\User::class, 'admin')->create([
             'email' => 'admin@abc.co.za',
             'password' => bcrypt('secreT5000'),
          ]);

          $normal_user = factory(RMS\User::class)->create([
              'email' => 'company@abc.co.za',
              'password' => bcrypt('secreT5000'),
           ]);
     }

     public function tearDown()
     {
         $this->artisan('migrate:reset');
     }

    /**
     * Test Successful Login
     *
     * @return void
     */
    public function testGoodAdminLogin()
    {
      $this->visit('/admin')
         ->type('admin@abc.co.za', 'email')
         ->type('secreT5000', 'password')
         ->check('remember')
         ->press('Login')
         ->seePageId('/dashboard')
         ->dontSee('These credentials do not match our records.')
         ->see('Users');
    }

    /**
     * Test Failed Login
     *
     * @return void
     */
    public function testFailedLogin()
    {
      $this->visit('/admin')
         ->type('admin@abc.co.za', 'email')
         ->type('secreT', 'password')
         ->press('Login')
         ->see('These credentials do not match our records.')
         ->seePageIs('/auth/login');
    }

    /**
     * Test Normal user positive Login
     *
     * @return void
     */
    public function testNormalUserLogin()
    {
      $this->visit('/admin')
         ->type('company@abc.co.za', 'email')
         ->type('secreT5000', 'password')
         ->press('Login')
         ->seePageIs('dashboard')
         ->dontSee('Users');
    }
}

However using the model save method the tests pass:

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class AuthTest extends TestCase
{
    //Run Migrations to Create Tables
    use DatabaseMigrations;

    public function setUp(){
      parent::setUp();
    }

    /**
     * Test Successful Login
     *
     * @return void
     */
    public function testGoodAdminLogin()
    {
      //Add the Test Admin User
      DB::table('users')->insert([
          'email' => 'admin@abc.co.za',
          'password' => bcrypt('secreT5000'),
          'is_admin' => true
      ]);

      $this->visit('/admin')
         ->type('admin@abc.co.za', 'email')
         ->type('secreT5000', 'password')
         ->check('remember')
         ->press('Login')
         ->seePageIs('/dashboard')
         ->see('Users');
    }

    /**
     * Test Failed Login
     *
     * @return void
     */
    public function testFailedLogin()
    {
      //Add the Test Admin User
      DB::table('users')->insert([
          'email' => 'admin@abc.co.za',
          'password' => bcrypt('secreT5000'),
          'is_admin' => true
      ]);

      $this->visit('/admin')
         ->type('admin@abc.co.za', 'email')
         ->type('secreT', 'password')
         ->press('Login')
         ->see('These credentials do not match our records.')
         ->seePageIs('/auth/login');
    }

    /**
     * Test Failed Login
     *
     * @return void
     */
    public function testNormalUserLogin()
    {
      //Add the Test User
      DB::table('users')->insert([
          'email' => 'company@abc.co.za',
          'password' => bcrypt('secreT5000'),
          'is_admin' => false
      ]);

      $this->visit('/admin')
         ->type('company@abc.co.za', 'email')
         ->type('secreT5000', 'password')
         ->press('Login')
         ->seePageIs('dashboard')
         ->dontSee('Users');
    }
}



via Chebli Mohamed

vendredi 29 juillet 2016

Angular Js with Laravel or Node Js

I am using Laravel 5.2.37 for CRUD. Blade are also implemented inside same code. I meant, database interaction and UI both are part of same project.

Question:

Somebody suggested me to use Angular Js for UI and backend for Laravel. Laravel should respond with JSON data only.

I never worked on Angular Js or Node Js. I have no idea if I should change the complete code before I keep developing the things as project is large so its better to decide at design kind of stage only.

Can you please suggest?



via Chebli Mohamed

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?



via Chebli Mohamed

defer running of a method until call

I'm using Laravel 5.1 and have created dynamic querying for filters.

I'm passing through the Model I'd like to query on, the filter fields (category_id, review, etc), and the values within those respective fields.

I'm passing in the field I'd like and getting its function TO BE run (don't run it yet):

$method = $this->getFilterForField($filter_field);

Then I'm calling the method with params:

$method($query, $filters_array, $user);

Query logger is telling me the queries are being run twice (see below).

How can I defer the method call until I actually want to run it with my params? Meaning, can I return a string representation of a method to be called at a later point?

Loop:

    $query = $model_class::query();
    foreach ($input as $filter_field => $filters_array) {

        //Get the method
        $method = $this->getFilterForField($filter_field);

        //Run method with params
        $method($query, $filters_array, $user);
        ...

Method:

public function getFilterForField($field)
{
    $filters = [
        'category_id' => function($query, $args, $user = null) {
            return $query->whereIn();
        },
        'review' => function($query, $args, $user = null) {
            if (in_array('yes', $args) && in_array('no', $args)) {
                return $query->orWhereHas();
            } else (in_array('yes', $args) && !in_array('no', $args)) {
                return $query->whereHas();
            }
        }
    ];

    return $filters[$field];
}


Query log if needed:

With $method = $this->getFilterForField($filter_field); AND $method($query, $filters_array, $user);:

enter image description here

Commented out the method call: $method($query, $filters_array, $user);

enter image description here



via Chebli Mohamed

How can I manage the Sximo Laravel CMS notifications

How can I manage the notifications using the Sximo Laravel CMS please. Can you help me to find a best tutorial ?

I will change my current project to receive notifications if a user change any thing in the database (comment, register ....)



via Chebli Mohamed

Laravel 5.1 migrate database to hosted mysql

How would I go about doing this (the title is the question), I've changed all my ENV files to my hosted mysql details. When i run php artisan migrate from composer I get the

"denied username@localhost using password yes error".

I've changed the port and everything but I'm not sure what to do anymore and I'm 99% sure that the details are correct I've tried them multiple times



via Chebli Mohamed

WAMP Sub domain routing with laravel

I am using laravel 5.1 & WAMP server 2.5.

I have my domain like 'www.example.com' which is pointing to the root. where else I have a subdomain like 'admin.examle.com'.

Route::group(['prefix' => 'app', 'middleware' => 'authentication'], function () {
        Route::get('home', ['as' => 'app.home', 'uses' => 'DashboardController@home']);
    });

I have added virtual hosts on httpd-vhosts.conf as below:

<VirtualHost *>
    ServerName www.example.com
    ServerAlias example.com
    DocumentRoot "C:/wamp/www"
</VirtualHost>

<VirtualHost *>
    ServerName example.com
    DocumentRoot "C:/wamp/www/app"
    ServerAlias app.example.com
</VirtualHost>

But as app is not an actual folder in my www folder it is showing internal server error. Can anyone help with this ?? I need to use subdomains for the same.



via Chebli Mohamed

Laravel Groupby return count instead of each row value

I am working with laravel 5.2 and can't get this query to work. I have a fruit table, with a column fruit name. I want to group by fruit name .But I have the model named Fruit also, I am getting the count of each repeated fruit name but I want each row value , example apple is selected by 5 members means ,then I must need all member values correspond to apple , but I am currently getting only on value.Can you please write query for my case.



via Chebli Mohamed

jeudi 28 juillet 2016

Make Shopping Cart in Laravel

in there i want to add shopping cart in my project. i have try make it but its still want work.

this my controller :

function postCreate(){

        echo '<pre>';
        print_r(Request::all());
        exit;
        $data['list'] = DB::table('package')
        ->join("cms_car","cms_car.id","=","package.id_cms_car")
        ->join("zone","zone.id","=","package.id_zone")
        ->select("package.*","cms_car.car as name_car","cms_car.photo as car_photo");       


        return view('detail',$data);
    }

and here my view for listing :

 @if ($row->driver == 'Driver Included')
          <img src="" style="max-width:15px;">
        @else

        @endif

         </p>
        <p>
        @if ($row->driver == 'Driver Included')
          <img src=""style="max-width:15px;"> 
        @else

        @endif
        </p>
        <h6 class="post-price">price :</h6>
        <p>Rp. </p>
    </div>
</div>
<hr>
<div class="col-md-6">
Unit Quality :<br><br>
    <div class="input-group" style="width: 150px;">
<span class="input-group-btn">
              <button type="button" class="btn btn-danger btn-number btn-minus"  data-type="minus">
                <span class="glyphicon glyphicon-minus"></span>
              </button>
          </span>
          <input type="text" name="quantity" class="form-control input-number" value="1" data-price="" data-id="" min="1" max="100">
          <span class="input-group-btn">
              <button type="button" class="btn btn-success btn-number btn-plus" data-type="plus">
                  <span class="glyphicon glyphicon-plus"></span>
              </button>
          </span>
</div>
</div>

<div class="col-md-6">

   <h3 style="margin-top:40px" id="price">Rp. </h3>
</div>
  </div>
  </div>
  @endforeach

in there i want to make cart it only add when i change the unit quantity

form input name : quantity

my webview

have someone tell me what improvements do i have to make to the code to achieve my goal?



via Chebli Mohamed

Laravel number comparison in 'where' not working

I have a Laravel 5.1 app, and am having trouble with a 'where' with a numerical comparison. Specifically I am trying to do:



The SQL 'type' of paid_price is 'decimal(8,2)'. There are several Item rows where the paid_price is in fact greater than zero, but the code above just yields 0. Stuff like the below which don't rely on numerical comparisons works just fine - can you give me any tips on why the > doesn't work? Thanks a lot



The code for my Items class is below:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Items extends Model {
protected $fillable =['gateway','paid_price','payment_date','auth_date','charge_date','refunded_date'];
protected $dates = ['payment_date','auth_date','charge_date','refunded_date'];
public function setUserIdAttribute($value)
{
    $this->attributes['user_id'] = $value ?: null;
}
}



via Chebli Mohamed

mercredi 27 juillet 2016

Laravel 5.1 using storage to move the file to a public folder

In my Laravel API call, I use Storage to upload a file. Then I wold like to rename and move the file to a public directory by using $dest = '/var/www/public/uploads/';

Storage::disk('local')->put($filename.'.'.$extension,  File::get($file));
$oldfilename = $filename.'.'.$extension;
Storage::move($oldfilename, $dest.$newImageName);

But instead of moving the file to the $dest directory, I get a folder created with the $dest dir name inside my storage/app folder and the file is copied there. I have also tried using double quotes around $dest.$newImageName but no success.



via Chebli Mohamed

Multiple table inheritance in Laravel 5.1

I've read some comments about how to implement multiple table inheritance in Laravel, but I'm confusing.

In this thread (Table inheritance in Laravel), I noted that a table inheritance was implemented. However, Laravel 5.1 documentation explains about "Polymorphic Relations" (http://ift.tt/1RvSF2y).

This is my scenario: A "Person" can be a "Student", "Teacher" and/or "Candidate". The same person can be Student and Teacher at the same time, for example. This is a way to implement the models I think (I do not know if it is correct):

class Person extends Model {
    public function teacher(){
        return $this->hasOne(Teacher::class);
    }
    public function student(){
        return $this->hasOne(Student::class);
    }
    public function candidate(){
        return $this->hasOne(Candidate::class);
    } 
}

class Student extends Person {
    public function person(){
        return $this->belongsTo(Person::class);
    }
}

class Teacher extends Person {
    public function person(){
        return $this->belongsTo(Person::class);
    }
}

class Candidate extends Person {
    public function person(){
        return $this->belongsTo(Person::class);
    }
}

In the database, I would create the tables:

  • Person (id, name, phone)
  • Student (person_id, etc)
  • Teacher (person_id, etc)
  • Candidate (person_id, etc)

This way, I do not use Polymorphic Relations as Laravel 5.1 explains. Any suggestions about the best way to accomplish this?

Thank you very much.



via Chebli Mohamed

PHP / MySQL: do tasks based on schedule in database

I would like to have a database with weekly PHP tasks that can be set by the user. As an example the user could create a task "Send Email" every Friday at 10am in time-zone GMT+5.

I want to create a PHP script that searches the database for tasks that need to be executed just now. What would be the proper way set up the database and to search the database for tasks to be executed?

The major issues are that (1) the tasks are repeating weekly and are not set to a fixed date/time and (2) different time-zones have to be considered (which prevents filtering based on the current weekday).

My initial plan was to use a database of task|timezone|weekday|time, but other suggestions are welcome.



via Chebli Mohamed

Eloquent\model injection into method returns null

I have problem with fetching model using injected Eloquent into controllers method - it dosne't find model using id in URL - dd($infrastructure) returns just meta data about Model:

Infrastructure {#257 ▼
#table: "infrastructures"
#fillable: array:10 [▶]
#connection: null
#primaryKey: "id"
....
} 

My controllers method:

public function show(Infrastructure $infrastructure, Request $request)
{

    $card = [];
    $card['name'] = $infrastructure->name;
    $card['id'] = $infrastructure->id;
    $card['type'] = "infrastructure";
    $card['items']['manufacturer'] = $infrastructure->manufacturer;
    $card['items']['type'] = $infrastructure->infrastructuretype()->first()-   >name;
    $card['items']['kind'] = $infrastructure->kind()->first()->name;
    $card['items']['serial'] = $infrastructure->serial;
    $card['items']['more info'] = Crypt::decrypt($infrastructure->long_desc);

    $title = 'Infrastructure details ';

    $warranty_left = $infrastructure->warranty_date > $infrastructure->purchase_date ? (new Carbon($infrastructure->warranty_date))->diffInDays(new Carbon($infrastructure->purchase_date)) : 0;

    return view('infrastructure.show', compact('infrastructure', 'card', 'title'));
}

My routes:

Route::model('infrastructure', 'App\Infrastructure');


Route::group(['middleware' => 'auth'], function () {
Route::resource('infrastructure', 'InfrastructureController');
get('infrastructure/{infrastructure}/logs', [
    'uses' => 'InfrastructureController@showInfrastructureLogs'
]);
resource('infrastructuretype', 'InfrastructureTypeController');


Route::get('auth/logout', 'Auth\AuthController@getLogout');

});



via Chebli Mohamed

Laravel 5.1 passing data to mail view doesn't work

So, I'm tryting to make an e-mail view, using data the user posted. The problem is, that specific data is unreachable. I don't know how I'm suppost to get that data.

Here is my controller:

public function PostSignupForm(Request $request)
    {
         // Make's messages of faults
        $messages = [
            //removed them to save space
        ];

        //Validation rules
        $rules = [
            //removed them to save space
        ];


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

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

        DB::table('rittensport')->insert([
            'note' => $request->get('note'),
            //standard instert
        ]);

        /**
        * Sending the e-mails to the pilot and co-pilot
        *
        * @return none
        */
        Mail::send('emails.rittensport_signup', $request->all(), function ($message) {
            $message->from(env('APP_MAIL'), 'RallyPodium & Reporting');
            $message->sender(env('APP_MAIL'), 'RallyPodium & Reporting');
            $message->to($request->get('piloot_email'), strtoupper($request->get('piloot_lastname')).' '.$request->get('piloot_firstname'));
            $message->to($request->get('navigator_email'), strtoupper($request->get('navigator_lastname')).' '.$request->get('navigator_firstname'));
            $message->subject('Uw inschrijving voor de RPR Gapersrit '. date('Y'));
            $message->priority(1);//Highest priority (5 is lowest).
        });

        return Redirect::back();

Well, The view exists and the error I'm facing to is: Undefined variable: request.

This is how I try to get the data in the e-mail view: I already tried things like , $message['note'] And so on... Can someone PLEASE help me out?



via Chebli Mohamed

how to increase the login time in laravel

hi i'm having a serious problem in my admin panel , every time i try to update,delete or insert data into database it redirect me to the login page again and that's wrong so how can i keep the user logged in , another problem is it always gives me the "verisfy csrf token " when i make a lot of changes and i put the in each form so what's the problem ? i tried to increase the session time to 1200 but it doesn't work so can anyone help me please ?



via Chebli Mohamed

mardi 26 juillet 2016

how to assign created_at only date string in laravel

I Have a problem with the created_at and other carbon dates, when I do

return $return_items['created_date'] = $item->created_at;

It returns '2016-07-26 13:19:55'

but if I do

return $return_items;

it returns

"created_date": {
   "date": "2016-07-26 13:22:17.000000"
   "timezone_type": 3
   "timezone": "UTC"
}

How can I solve this, to only show the string date?

thanks



via Chebli Mohamed

Session issue in Laravel 5.1

My app is built with Laravel 5.1. I have saved some data in session using the code, session(['first_name' => Auth::user()->first_name]). The value is set when user is logging in. It's working most of the times but sometimes the session value is being null. I don't know why automatically the session value is getting null. I am tired of solving this kind of weird problem. I need help.



via Chebli Mohamed

pagination not working when clicking on page number

I am using laravel pagination. When I click on next page or any page number, nothing happens. Controller function

public function getIndex()
{
    $articles = Inspector::paginate(15);
    return view('admin.inspector.test', compact('articles'));
}

View file

     <table class="table table-bordered" id="mytable">
                        <thead>
                            <tr>
                                <th>Sr. No.&nbsp;</th>
                                <th>Email</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach ($articles as $article)
                            <tr>
                            <td></td>
                            <td></td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                    {!! $articles->render() !!}

Any help is much appreciated...Thanks...



via Chebli Mohamed

How to chunk a sheet which is selected by id in Laravel 5.1

I'm using Laravel 5.1 and ~2.1.0 version of Laravel-Excel. I was importing a xlsx file with various sheets, which can have more than 400 rows like this:

        $reader = Excel::selectSheetsByIndex(0)->load($file, function ($reader)
        {
            return $reader;
        })->toArray();

And it works but the waiting time is too long so I tried to chunk sheets one by one as I've read that chunking multiple sheets wasn't supported yet. But it always returns 0 rows.

$reader = Excel::filter('chunk')->selectSheetsByIndex(0)
          ->load($file)
          ->select($columns)
          ->chunk(250)
          ->toArray();

Can someone tell me what's the problem?



via Chebli Mohamed

laravel 5.1 seed with class parameter

I Use laravel 5.1 , I received "Class MySeederClass does not exist " when use --class in php artisan db::seed(like php artisan db::seed --class=MySeederClass) , but when I run this command without class parameter, every thing is ok, what is this parameter problam??



via Chebli Mohamed

lundi 25 juillet 2016

Laravel Raw Query with Location, Join, and Pagination

I am using Laravel 5 to build functionality to allow a user to search for specials from vendors that are near their location. I have a table that holds vendors with their locations and another table that holds specials that vendors are offering. The specials table has a vendor_id column to link to the vendors table.

vendors (id, name, latitude, longitude) - some fields omitted
specials (id, name, description, vendor_id) - some fields omitted

I am trying to run a query that uses the latitude and longitude from the vendors table and also joins the specials table to get all information for a special including the vendor name and id (so that I can link to the vendor later). Below is my controller that I have so far.

public function postSearch(Request $request)
{
    DB::enableQueryLog();

    $specials = $this->special->with('vendor')->newQuery();

    if ($request->has('zip')) {
        $response = \Geocode::make()->address($request->input('zip'));
        $latitude = $response->latitude();
        $longitude = $response->longitude();
    } else {
        $latitude = $request->input('latitude');
        $longitude = $request->input('longitude');
    }

    $radius = ($request->input('radius') * 1.1);

    if ($request->has('category')) {
        $specials->where('category_id', $request->input('category'));
    }

    $specials->select(DB::raw("*, (3959 * acos(cos(radians(" . $latitude . ")) * cos(radians(vendors.latitude)) * cos(radians(vendors.longitude) - radians(" . $longitude . ")) + sin(radians(" . $latitude . ")) * sin(radians(vendors.latitude)))) AS distance"))->having('distance', '<', $radius);

    $now = date('Y-m-d H:i:s');
    $specials->where('end_date', '>', $now);

    $discounts = $specials->orderBy('distance')->get();

    dd(DB::getQueryLog());

    $body = View::make('main.specials.table', ['discounts' => $discounts])->render();

    return response()->json(['discounts' => $discounts, 'body' => $body], 200);
}

The query log is not returning anything for me to analyze. On top of joining the vendors table with the specials table I also need to paginate the results. I'm drawing blanks on how to accomplish this. Any help is appreciated.



via Chebli Mohamed

Trying to get property of non-object in Foreach loop: Laravel 5.2

I have following code.

@foreach($Countries as $Country)
    {!! $Country->Currency->Currency !!}
@endforeach

It shows error : Trying to get property of non-object on this line $Country->Currency->Currency

When I print the value using below code

@foreach($Countries as $Country)
    {!! dd($Country->Currency); !!}
@endforeach

It show value. It is below

CurrencyModel {#320 ▼
  +table: "tblcurrency"
  +primaryKey: "CurrencyID"
  +timestamps: true
  #connection: null
  #keyType: "int"
  #perPage: 15
  +incrementing: true
  #attributes: array:7 [▼
    "CurrencyID" => 1
    "Currency" => "INR"
    "CountryID" => 1
    "Symbol" => "₹"
    "IsActive" => 0
    "created_at" => "2016-07-25 06:36:42"
    "updated_at" => "2016-07-25 06:39:52"
  ]
  #original: array:7 [▶]
  #relations: []
  #hidden: []
  #visible: []
  #appends: []
  #fillable: []
  #guarded: array:1 [▶]
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  #morphClass: null
  +exists: true
  +wasRecentlyCreated: false
}

But, when I try like below

@foreach($Countries as $Country)
    {!! $Country->Currency->Currency !!}
@endforeach

I get this error: Trying to get property of non-object

Am I missing something?



via Chebli Mohamed

Laravel (5.1) query builder does not properly add bindings to a raw select statement

I'm using Laravel 5.1 and have the following simple query:

$searchTerm = 'random word';

$subQuery = DB::table('userprofile')->selectRaw("
    user_id,
    MATCH(first_name, last_name) AGAINST('?*' IN BOOLEAN MODE) AS search_score
")
->addBinding($searchTerm)
->get();

This returns nothing, but when I directly replace the quotation mark with

... AGAINST('$searchTerm*' IN BOOLEAN MODE) ...

then the results are correct. However, if I do

DB::getQueryLog();

I get

"query" => "select `user_id`, MATCH(first_name, last_name) AGAINST('?*' IN BOOLEAN MODE) AS search_score from `userprofile`"
"bindings" => array:1 [
  0 => "random word"
]

so it's as if the bindings should be added, but they're not. I have tried all variations of select, selectRaw, ->setBindings, ->addBinding($searchTerm, ['select']) etc. that have been suggested elsewhere. How can I make these bindings work?



via Chebli Mohamed

Make users sends emails to each others internally

I'm kind of beginner in laravel 5.1. My question is if I have users in an (paypal like) website and I want to make them sending money to each other via email. How can I do that ??

thanks in advance.



via Chebli Mohamed

Show success/error message on dropzone file upload

I am using dropzone file upload, when I return success / error from controller, how do I show it on my view file..

View file ,

 <div class="box-body">
    @if ( $errors->count() > 0 )
    <div class="alert alert-danger alert-dismissible">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
        
    </div>
    @endif

{!! Form::open([ 'url' => 'admin/reports','class' => 'dropzone', 'id' => 'reportfile' ]) !!}
    {!! csrf_field() !!}
    <div class="col-md-12">
        <h3 style="text-align : center">Select File</h3>
    </div>
    <button type="submit" class="btn btn-primary">Upload Report</button>
    {!! Form::close() !!}

</div>

Controller Code

if ($request->hasFile('file')) {
        $file = Input::file('file');
        $validator = Validator::make(
                        [
                    'file' => $file,
                    'extension' => strtolower($file->getClientOriginalExtension()),
                        ], [
                    'file' => 'required',
                    'extension' => 'required|in:csv',
                        ]
        );
        if ($validator->fails()) {

            return Response::json('error', 400);

        }

JS Code

<script>
window.onload = function () {

    Dropzone.options.reportfile = {
        paramName: "file", 
        maxFilesize: 2,
        error: function (file, response) {
            alert('hiii')
        },
        init: function () {
            this.on("addedfile", function (file) {
                alert("Added file.");
            });
        },
        accept: function (file, done) {
            alert('hi')
            if (file.name == "justinbieber.jpg") {
                done("Naha, you don't.");
            }

        }

    };
};
</script>

Not even alert is working...any help is much appreciated..Thanks



via Chebli Mohamed

Laravel form submit showing MethodNotAllowedHttpException in RouteCollection.php line 218:

This is my route

Route::resource('admin/reports', 'ReportController');

This is controller function

public function store(Request $request)
{
    return "Thank you";
}

This is my html code

{!! Form::open([ 'url' => 'admin/reports/store', 'files' => true, 'enctype' => 'multipart/form-data', 'class' => 'dropzone', 'id' => 'reportfile' ]) !!}
    {!! csrf_field() !!}
    <div class="col-md-12">
        <h3 style="text-align : center">Select File</h3>
    </div>

    <div class="col-md-12" style="text-align: center; padding: 10px">
        <button type="submit" class="btn btn-primary">Upload Report</button>

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

When I submit the form, it show me MethodNotAllowedHttpException in RouteCollection.php line 218:

Any help is much appreciated. Thanks



via Chebli Mohamed

Laravel exceptions handler best practice

I'm working on a project with laravel, exceptions are getting catched in the Exceptions\Handler.php inside the render function like so:

public function render($request, Exception $e){
      switch(get_class($e)){
              case SOME_EXCEPTION::class:
                    do something..
              ...
              ...
              default:
                    do something..
     }

The problem as you can see it's getting ugly and messy code with lot of cases

What is the best practice to avoid this situation?

Can you give an example how to solve this out?

Thanks!



via Chebli Mohamed

dimanche 24 juillet 2016

Laravel5.1, Relation, EloquentORM, Many to Many, Sort

<table border="true">
  <tr>
    <th style="width:100px">Table</th>
    <th colspan="3" style="width:300px">Columns</th>
  </tr>
  <tr>
    <td style="width:100px">Articles</td>
    <td style="width:100px">id</td>
    <td colspan="2" style="width:200px; color: #aaaaaa">other dependent variables</td>
  </tr>
  <tr>
    <td style="width:100px">Article_Tag</td>
    <td style="width:100px">id</td>
    <td style="width:100px">article_id</td>
    <td style="width:100px">tag_id</td>
  </tr>
  <tr>
    <td style="width:100px">Tags</td>
    <td style="width:100px">id</td>
    <td style="width:100px">name</td>
    <td style="width:100px"></td>
  </tr>
</table>

Then, I want to sort Articles table by [name] of Tags table. I tried eager-loading with closure below, but it did'nt work. Model Article and Tag are connected with each other just by belongsToMany, and I succeed in output their data, but they weren't sorted.Offcourse, I did'nt give getTag any argument.

use App\Article;
use App\Tag;

...

public function __construct(Article $article)
{
  $this->article = $article;
}

...

public function getTag($tag = NULL)
{  
$flag = isset($tag);

$articles = $this->article->orderBy('created_at', 'desc')->with([
    'tags' => function($query) use ($flag, $tag){
        ($flag)
            ? $query->where('name', $tag)
            : $query->orderBy('name');
    }
])->paginate(15);



via Chebli Mohamed

Trying to implement Repository Pattern in Laravel 5.2

Controller class

class SportsTypeController extends \App\Http\Controllers\BaseController
{
    private $sportstype;

    public function __construct(ISportsType $_sportstype) {
        $this->sportstype = $_sportstype;
        parent::__construct();
    }

    public function index() {
        $SportsTypes = $this->sportstype->All();
        return view('SportsType.List')->with('SportsTypes', $SportsTypes);
    }
}

Business logic class

class SportsTypeBL implements ISportsType {       

    public function All() {
        $SportsTypes = (new SportsTypeDb())->All();
        return $SportsTypes;
    }
}

Database class

class SportsTypeDb {

    public function All() {
        $SportsTypes = \App\Models\SportsType\SportsTypeModel::all();
        return $SportsTypes;
    }
}

Interface

public interface ISportsType {
     public function All();
}

Am I writing bad or very bad code? Can you please suggest good ways to improve it?



via Chebli Mohamed

Is there a way in Laravel to manage the files that are going to be downloaded by the server?

I saw that drupal 7 has a method where you can choose which libraries are going to be downloaded in an specific module "drupal_add_js()". I was wondering if laravel has something similar, what I did is to put a switch case in my main blade template, but in order to compress and minify a js file, I have to create a minified specific version of the js in my gulp file. And isn't the most optimal solution. Thanks in advance.



via Chebli Mohamed

laravel does not get session in backbone.js request

I use laravel 5.1 for backend and backbone.js for front I add CORS middleware to kernel.php and comment verifycsrf middleware, my problam is requests from backbone does not contain session in headers so authentication faile, do you have any idea?!



via Chebli Mohamed

samedi 23 juillet 2016

Laravel Route not working error is Trying to get property of non-object

I have now working on a project called Hospital & Doctor Information. Here I have different Division in Bangladesh & in each division there are districts in which there are certain types of hospital according to their ownership. But when I get the value of different hospital from it shows me some error. My route file

Route::get('/', array('as' =>'home' ,'uses' => 'UserController@index'));

Route::get('/about_us', array('as' =>'about_us' ,'uses' => 'UserController@about_us'));

Route::get('/district/{id}', array('as' =>'district' ,'uses' => 'UserController@district'));

Route::get('/district/hospital/{id}', array('as' =>'hospital' ,'uses' => 'UserController@hospital'));

Route::get('/district/hospital/hospital_info/{id}', array('as' =>'hospital_info' ,'uses' => 'UserController@hospital_info'));

My Controller is

public function hospital($id)
{

     $divisions = Division::all();
     $division=Division::find($id); 

     $district=District::find($id); 

     $categories=Category::all();

    // $districts=District::where('division_id', '=', $divisions->id)->get();

    // if (!$district)
    // {
    //     throw new NotFoundHttpException;
    // }
    return view('users.hospital')
                ->with('divisions',  $divisions)
                ->with('division', $division)
                ->with('district', $district)
                ->with('categories',$categories);
}


public function hospital_info($id)
{
    $divisions = Division::all();
     $division=Division::find($id); 

     $district=District::find($id); 

     $categories=Category::all();
     $hospitals=Hospital::find($id); 

    // $districts=District::where('division_id', '=', $divisions->id)->get();

    // if (!$district)
    // {
    //     throw new NotFoundHttpException;
    // }
    return view('users.hospital_info')
                ->with('divisions',  $divisions)
                ->with('division', $division)
                ->with('district', $district)
                ->with('categories',$categories)
                ->with('hospitals',$hospitals);
}

My view file is

    <?php $active="hospital"; ?>
@extends('layouts.dashboard')
@section('content') 

    <section id="blog" class="container">
        <div class="center">
            <h2>Hospital Information</h2>
            <h3 class="lead">The government approved a renowned hospital and improved quality of service address , doctor , patient viewing time, bed , pathological tests in various subjects including costs and find the information here .<br> The bed and cabin bookings online , pathological tests , the doctor can be a serial for the meeting from the app .</h3>
        </div>

        <div class="blog">
            <div class="row">
                 <div class="col-md-12">
                    <div class="blog-item">
                        <div class="row">

                            <div class="col-xs-12 col-sm-4 blog-content">

                                <a href="#"><img class="img-responsive img-blog" src="images/2.jpg" width="100%" alt="" /></a>
                            </div>
                            @foreach($division->districts as $district)
                                @foreach($district->categories as $category)
                                    @foreach($dcategory->$hospitals as $hospital)
                                    <div class="col-xs-12 col-sm-6 blog-content">
                                        <h2></h2>
                                    </div>
                                    @endforeach
                                @endforeach
                            @endforeach


                    <ul class="pagination pagination-lg">
                        <li><a href="#"><i class="fa fa-long-arrow-left"></i>Previous Page</a></li>
                        <li class="active"><a href="#">1</a></li>
                        <li><a href="#">2</a></li>
                        <li><a href="#">3</a></li>
                        <li><a href="#">Next Page<i class="fa fa-long-arrow-right"></i></a></li>
                    </ul><!--/.pagination-->
                </div><!--/.col-md-8-->

            </div><!--/.row-->
        </div>
    </section><!--/#blog-->
@stop

& MY Model is Hospital.php

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Hospital extends Model
{

    protected $fillable = [
        'name',
        'division_id',
        'district_id',
        'category_id',
    ];

    public function district()
    {

        return $this->belongsto('App\District');
    }
}

District.php

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class District extends Model
{
    protected $fillable=[
        'name',
        'division_id',
    ];



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

    public function category()
    {
        return $this->hasmany('App\Categories');
    }
    public function dcategory()
    {
        return $this->hasmany('App\Dcategories');
    }

    public function hospital()
    {
        return $this->hasmany('App\Hospital');
    }
}

the error is enter image description here

Please Help Me. Thanks in advance



via Chebli Mohamed

Laravel5.1: hide a portion of code form view

Here I've a portion of code which I don't want to show in the user interface.

<div class="form-group">
     <label for="customer_id" class="col-sm-4 control-label"></label>
     <div class="col-sm-8">
          {!! Form::select('customer_id', $customer, Input::old('customer_id'), array('class' => 'form-control')) !!}
     </div>
</div>

I want this section to be hidden. Laravel form has form::hidden() method to do this but how can I apply this in my form::select() method. Thanks in advance.



via Chebli Mohamed

Make view of a page in laravel 5.1 using routes

I am trying to get a view page without passing extra parameters in url

routes.php

Route::controller('site','SiteController');

menu.php

<li><a href="">Home</a></li>
<li><a href="">About</a></li>
<li><a href="">Contact</a></li>

SiteController.php

public function index(){

return view('welcome');
}
public function getAbout(){

return view('about');
}

when i am trying to access my about page the URL is coming like http://localhost/fitness/public/site/about but here how can modify my code to get URL like http://localhost/fitness/public/about .It is happening for all other pages. I do not want to write get and post method in routes page.My routes page should remains with same code.I do not want site to come in URL .

will this possible ?? Can anybody help me out ?

Thank you.



via Chebli Mohamed

how to set Laravel 5.1 project url?

I am using Laravel 5.1 , when I want to use laravel in localhost ( wampserver) I can access to my project by this address :

by running php artisan serve command : http://localhost:8000

and in this way every thing is ok and all packages work well ! but when I do not want to run php artisan serve I can access to project by removing public from url by this way by this address : http://localhost/myblog and also I can upload my project on shared hosting easily ! but I have big problem here ! when I want to use filemanager package or other packages , I noticed that thay can not recognize project url. for example they consider http://localhost is the project's url ! how can I fix this ? I don't want to use SSH and run composer on hosting !



via Chebli Mohamed

vendredi 22 juillet 2016

get the data from the resultant in laravel eloquent

I have these tables
categories_branch
categories
categories_branch_relation
locale

using categories_branch_relation table to get record it has both foreign keys. now problem is to pick the record from the categories table (lang_locale_text_id) from other table.

my query result is

[0] => Array
    (
        [id] => 1
        [category_id] => 1
        [category_branch_id] => 1
        [categorydata] => Array
            (
                [id] => 1
                [name] => Elektrotechnik
                [description] => Elektrotechnik
                [rating] => 0
                [datetime] => 2016-06-27 00:00:00
                [visible] => 1
                [lang_locale_text_id] => 4
            )

    )

how i can get data from (lang_locale_text_id) from other table ?



via Chebli Mohamed

PHPUnit with Laravel, expected exception breaks Mockery expectations?

Controller code:

public function getIndex($resource) {
    $r = $this->mapper->map($resource);
    if (! $r) {
        throw new \Exception("Resource not found.");
    }
}

This is my test:

public function testGetIndex_if_resource_is_not_found() {
    $this->mapper->shouldReceive('map')->with('foo')->once()->andReturnNull();
    $this->setExpectedException('Exception');
    $this->call('GET', 'resources/foo');
}

I get this:

Mockery\Exception\InvalidCountException: Method map("foo") from Mockery_0_Foothing_RepositoryController_Resources_Mapper should be called
 exactly 1 times but called 0 times.

If i disable the expectation on the exception like this:

public function testGetIndex_if_resource_is_not_found() {
    $this->mapper->shouldReceive('map')->with('foo')->once()->andReturnNull();
    // $this->setExpectedException('Exception');
    $this->call('GET', 'resources/foo');
}

the test output will be

Exception: Resource not found.

Seems like i can't having both expectations to work :/ What's broken in my code?



via Chebli Mohamed

Class Does not exist

I am having the following error

InvalidArgumentException in FormBuilder.php line 39: Form class with name App\Http\Controllers\App\Forms\SongForm does not exist.

on Laravel,

SongsController.php class

<?php

namespace App\Http\Controllers;

use Illuminate\Routing\Controller as BaseController;
use Kris\LaravelFormBuilder\FormBuilder;

class SongsController extends BaseController {

    public function create(FormBuilder $formBuilder)
    {
        $form = $formBuilder->create(App\Forms\SongForm::class, [
            'method' => 'POST',
            'url' => route('song.store')
        ]);

        return view('song.create', compact('form'));
    }

    public function store(FormBuilder $formBuilder)
    {
        $form = $formBuilder->create(App\Forms\SongForm::class);

        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }

        // Do saving and other things...
    }
}

SongForm.php

<?php

namespace App\Forms;

use Kris\LaravelFormBuilder\Form;

class SongForm extends Form
{
    public function buildForm()
    {
        $this
            ->add('name', 'text', [
                'rules' => 'required|min:5'
            ])
            ->add('lyrics', 'textarea', [
                'rules' => 'max:5000'
            ])
            ->add('publish', 'checkbox');
    }
}

routes.php

Route::get('songs/create', [
    'uses' => 'SongsController@create',
    'as' => 'song.create'
]);

Route::post('songs', [
    'uses' => 'SongsController@store',
    'as' => 'song.store'
]);

And I do not know where is the problem because the file exist in the project folder.



via Chebli Mohamed

How to connect to remote server in laravel

I am trying to connect to other db server in laravel, i changed the host and port in my database.php but it is not working can any one suggest help.

This is my database.php:

'mysql' => array(
        'driver'    => 'mysql',
        'host'      => '192.168.1.6',
        'port'      => '3306',
        'database'  => 'ired4',
        'username'  => 'root',
        'password'  => 'root',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',

    ),

I am getting the following error:

PDOException (2002)
SQLSTATE[HY000] [2002] Connection refused



via Chebli Mohamed

jeudi 21 juillet 2016

Issue coming when sending validation Errors back to page: Laravel 5.2.37

My Routes are below

Route::get('/me/{UserName}', array('uses' => 'Website\Account@index', 'as' => 'Profile'));
Route::post('/UpdateProfile', 'Website\Account@UpdateProfile');

My Request class has below code

protected function getValidatorInstance()
{
    $instance = parent::getValidatorInstance();
    $instance->after(function ($validator) {
        $this->IsValidPassword($validator);
    });
    return $instance;
}

public function IsValidPassword($validator)
{
    $Profile = \Auth::user();
    if(\Request::get( "EmailAddress" ) != $Profile->EmailAddress) {
        if(!\Hash::check(\Request::get( "Password" ), $Profile->Password)) {
            $validator->errors()->add('PasswordMismatch', 'Password is incorrect!');
        }
    }
}

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

Above code checks if the Password is incorrect then send the errors back to page.

Problem is : It does not go back to the page but below error is coming

HttpResponseException {#286 ▼
  #response: RedirectResponse {#289 ▶}
  #message: ""
  #code: 0
  #file: "C:\xampp\htdocs\Learning\vendor\laravel\framework\src\Illuminate\Foundation
                                                 \Http\FormRequest.php"
  #line: 107
  -trace: {▶}
}



via Chebli Mohamed

Laravel testing with group prefix

I have a group for api:

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

    Route::get('abc', function () {
        return 'abc';
    });
  );

But, when testing use $this->call('GET', '/api/abc) or $this->call('GET', 'path_to_abc'), I always get 404 error, although I've printed the url and I can visit that link on browser



via Chebli Mohamed

Using filp/whoops as a service provider in Laravel 5.1

I'm trying to integrate the filp/whoops package into Laravel 5.1 app.

Installed the package like this:

composer require filp/whoops:~1.0

Created app/Providers/ErrorServiceProvider.php like this:

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Whoops\Handler\PrettyPageHandler;
use Whoops\Run;

class ErrorServiceProvider extends ServiceProvider {

    public function boot()
    {
        $whoops = new Run;
        $whoops->pushHandler(new PrettyPageHandler);
        $whoops->register();
    }

    public function register()
    {
        //
    }

}

And registered the service provider in config/app.php like this:

'providers' => [
    App\Providers\ErrorServiceProvider::class
]

But I'm still seeing the default error pages.



via Chebli Mohamed

No database table is being migrated : Laravel 5.2

.env Database details are below.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=learning
DB_USERNAME=root
DB_PASSWORD=

Around 13 tables are present for migration. Below is the screenshot

enter image description here

So far there is no database table migrated.

Below is the result after executing the migration command

enter image description here

When I try php artisan migrate:refresh. Below is the screenshot

enter image description here

Problem is: No database table is being migrated.



via Chebli Mohamed

PHP - Subtract value from 2 arrays where key = is the same

Im not sure if ive wrote the question properly but ill elaborate more on what i need.

I have two arrays with keys 1,2,3 but they have different values i need to subtract the values from the array where the keys are the same, I hope this makes sense.

Things ive tried to far

  • Push them both to 1 array and do the math from there (can't figure out how to do this)
  • use array_diff to find the difference in the arrays but didn't work.

All help appreciated any more information needed will be provided



via Chebli Mohamed

how to continue number for all pages?

I have a project of laravel 5 , i want to continue the pages with numbering of each object, but when i visit next page then the ol number restarting from 1 , 2 ,3 etc again. My php code is given below -

  • subject_on_link_bar }}">
  • subject_on_link_bar }}/">
  • subject_on_link_bar }}//">
  • Questions & answers


  • via Chebli Mohamed

Laravel Reproduce an array given by the eloquent model

I am new in laravel. Right now i am struggling on how to redeclare the array given by the eloquent model.

PHP code

$data = Commission::select(['uploads_id'])->where([
            'affiliate_code' => $id
        ])->get()->toArray();
        var_dump($data);

var_dump Output

array(3) {
  [0]=>
  array(1) {
    ["uploads_id"]=>
    string(2) "24"
  }
  [1]=>
  array(1) {
    ["uploads_id"]=>
    string(2) "26"
  }
  [2]=>
  array(1) {
    ["uploads_id"]=>
    string(2) "27"
  }
}

i want the $data to be redeclare like this.

$data = [24 , 25 , 26]

is there a way on it or different approach?



via Chebli Mohamed

Laravel 5.2 - get images of item in blade view

My controller is:

public function index()

{

$details= Food::all();

return view('details.index', compact('details'));

}

public function show($Food_id)

{

 $detail=Food::findOrFail($Food_id);

 return view('details.show', compact('detail'));

}

My index.blade.php is:

<h1>Details</h1>

<hr/>  


@foreach($details as $detail)

<detail>

<h2>

<a href="/details/">

</a>

</h2>

</detail>

@endforeach

And my show.blade.php is:

 <h1 align="center"></h1>

<detail>

<h3><p>Name:</h3><h4></h4></p>

I want to show the images of food items that are stored in public/uploads folder.How I can get images to show them.



via Chebli Mohamed

Error when sending to 404 page : Laravel 5.2

My URL is below.

http://localhost:70/Learning/public/ededrf

My code is below.

public function report(Exception $e)
{
    $error = $e;
    if($e->getStatusCode() == 404) {
        \App::abort(404);
        return;
    }
    parent::report($e);
}

There is no such above URL in my route list. So it should give 404 error. But I am getting error attached below. .I have confirmed that the status code is coming 404. I got to know about it by writing dd($e->getStatusCode()); in report method.

Question: How can I redirect it to 404 page?

enter image description here



via Chebli Mohamed

How to handle laravel csrf when sending a Guzzle POST request?

I'm trying to send a POST request with Guzzle to a remote Laravel server. The problem is that the request will always be rejected due to the default Laravel csrf middleware.

The request is used to forward an image file that a user uploads from the main server to a server for storing images.

Is there a way to set the correct token using Guzzle?

If not would it be safe to turn off the csrf middleware for the images server as it only recieves requests from another server?



via Chebli Mohamed

mercredi 20 juillet 2016

[Laravel 5.1]Custom routes display a white (blank) page

Im currently using XAMPP (PHP 5.6.21) on a Win 10 machine.

Im doing a migration from a site in .net to laravel. Until now i almost had no problem, most of the previous problems came from inexperience. But i can't find solutions for this error.

routes.php

//Operaciones
Route::resource('operaciones', 'OperacionesController');
//Ruta al cierre de Operaciones
Route::any('operaciones/cerrar', ['as' => 'operaciones/cerrar', function(){
dd('asdasd');
}]);

The resource route works fine, but the 2nd route brings me a white (blank) page

And does not matter if i put anything in the web browser

if i put

http://localhost:8080/mutualv0/public/operaciones/asdasdasd

white page, if i put

http://localhost:8080/mutualv0/public/operaciones/cerrar

withe again...

But, if y try this

http://localhost:8080/mutualv0/public/operaciones2

NotFoundHttpException

I have nothing in the logs, i installed a laravel link checker and does not trow me any errors... i just don´t know what to do...



via Chebli Mohamed

Laravel 5.1 Intermittent State Exception

There have been several posts on SO regarding this issue and having tried all of the solutions I've found, I'm confident that there's specifically something wrong with my code. Here's the current iteration of my social login code for Google.

To be clear, this code works about 90% of the time. For about 10% of users on my site, they're triggering invalid state exception errors and can't log in.

I plan to rebuild the entire site on Laravel 5.3 next month so I just need this fix to last 30 days.

Here's my code:

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

    /**
     * Store a newly created resource in storage.
     *
     * @param Request $request
     * @return Response
     */
    public function store(Request $request)
    {
        $socialUser = Socialite::driver('facebook')->user();

        $user = User::firstOrNew(['socialite_provider' => 'facebook', 'socialite_id' => $socialUser->getId()]);
        $user->socialite_provider = 'facebook';
        $user->socialite_id = $socialUser->getId();
        $user->socialite_nickname = $socialUser->getNickname();
        $user->socialite_name = $socialUser->getName();
        $user->socialite_avatar = $socialUser->getAvatar();
        $user->socialite_email = $socialUser->getEmail();
        $user->save();

        /*
         * Hack to fix invalid state error, I think this helped a little but it's still not working for all users.
         */
        $state = $request->get('state');
        $request->session()->put('state', $state);
        if (Auth::check() == false) {
            session()->regenerate();
        }

        // Update orders so that we don't lose our guest cart
        $oldSessionId = Session::getId();

        Auth::login($user, true);

        $newSessionId = Session::getId();
        Order::updateSession($oldSessionId, $newSessionId);

        return redirect()->intended('/');
    }



via Chebli Mohamed

Event is not firing

I'm trying to fire event in my integration test but it is not triggering. I set up QUEUE_DRIVER=sync in my phpunit xml. Why is event and listener is not working ? The workflow of my app is next:

Create some entity. Send it to remote server (i use even and listener); Give back some id and write it to db.

 public function testCanGetCbdOfPlan() {
    $plan = factory(Plan::class)->create();

    $plan->save();

    Event::fire(new PlanSaveEvent($plan)); // There  cbd_id should be added to the $plan

    $this->assertNotEmpty($plan->cbd_id, 'CBD_ID is empty');
}



via Chebli Mohamed

Laravel 5.1 - get data from database group by id and sum values

Im not sure how to go about this, i need to get data from a table and sum the values of each field together where the ID is the same.

Things I Have Tried

  • Pulled all data and tried to store duplicates in array then sort it like that

$users = User::all();

   $array = [];
    foreach($users as $user)
        {
            array_push($array, [$user->account_id => $user->amount]);
        }

  • Use laravel collections to store the array data and sort it through there

Other than that im not too sure how to go about this! Here is the data that i pull from the database.

0: {1: 100.00}
1: {1: 100.00}
2: {2: 100.00}
3: {2: 100.00}

This is the output i want

0: {1: 200.00}
1: {2: 200.00}

This is all i need nothing else I feel like its really simple but I have no clue, any help and guidance will be appreciated, any further information needed will be provided.



via Chebli Mohamed

Dingo/API when Unit Testing: The version given was unknown or has no registered routes

I built an API using dingo/api 0.10.0, Laravel 5.1 and lucadegasperi/oauth2-server-laravel": "^5.1".

All my routes work fine in Postman/Paw!

The problem appears when I try to test the API using PHPUnit.

This is part of my route-api.php file

<?php

$api = app('Dingo\Api\Routing\Router');

$api->version(['v1'], function ($api) {

$api->post('oauth/access_token', function () {
    return response(
        \LucaDegasperi\OAuth2Server\Facades\Authorizer::issueAccessToken()
    )->header('Content-Type', 'application/json');
});

$api->group(['middleware' => ['oauth', 'api.auth']], function ($api) {
    $api->post('/register', 'YPS\Http\Controllers\Api\UserController@register');
});

And this is my test file UserRegistrationTest.php

class UserRegistrationTest extends ApiTestCase
{

public function setUp()
{
    parent::setUp();
    parent::afterApplicationCreated();
}

public function testRegisterSuccess()
{
    $data = factory(YPS\User::class)->make()->toArray();
    $data['password'] = 'password123';

    $this->post('api/register', $data, $this->headers)
        ->seeStatusCode(201)
        ->seeJson([
            'email' => $data['email'],
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
        ]);
}

public function testRegisterMissingParams()
{
    $this->post('api/register', [], $this->headers, $this->headers, $this->headers)->seeStatusCode(422);
}
}

The ApiTestCase simply retrieves a token and sets the headers.

private function setHeaders()
{
    $this->headers = [
        'Accept' => 'application/vnd.yps.v1+json',
        'Authorization' => 'Bearer ' . $this->OAuthAccessToken,
    ];
}

Now, the weird part is that the first test testRegisterSuccess runs perfectly and returns the response I expect. But the second one testRegisterMissingParams, even though it's the same route, returns this,

array:2 [
      "message" => "The version given was unknown or has no registered routes."
      "status_code" => 400
 ] 

I tracked the error and it is in the Laravel adapter here:

public function dispatch(Request $request, $version)
{
    // it seems that the second time around can't find any routes with the key 'v1'
    if (! isset($this->routes[$version])) {
        throw new UnknownVersionException;
    }

    $routes = $this->mergeExistingRoutes($this->routes[$version]);

    $this->router->setRoutes($routes);

    return $this->router->dispatch($request);
}

And further more, if i run one test at a time (eg comment one out, run test and then comment the other and run test) i see the result expected in both tests. The problem is when i run multiple tests.

Any thoughts on that?

Thank you!



via Chebli Mohamed

mardi 19 juillet 2016

Add Save Facade that will add to config in laravel

I've been using laravel config writer package http://ift.tt/29TxaKO that will edit and save config and I want to add new Facade that will add new (data, value) in config which is always says "Unable to rewrite key "key" in config, does it exist?

I've been add this below code to ConfigWriter\Repository.php

public function toFile($filePath, $newValues, $useValidation = true)
{
    $contents = file_get_contents($filePath);
    $contents = $this->toContent($contents, $newValues, $useValidation);
    file_put_contents($filePath, $contents);
    return $contents;
}



via Chebli Mohamed

Laravel 5.1.26 Composer Update Error

Getting Error while updating Composer.json in Laravel 5.1.26, I have added a package tcpdf and also tried using the latest version of tcpdf it also showing error,

[RuntimeException]
Could not load package intervention/image in http://packagist.org: [UnexpectedValueException] Could not parse version constraint 4.x.x: In valid version string "4.x.x"

And also tried composer self-update command but says it throws a message.

[InvalidArgumentException] Command "self-update" is not defined.

Donno how to resolve it, this is my composer file with tcpdf package added.

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*",
        "illuminate/html": "5.0.*@dev",
        "laravel/socialite": "^2.0",
        "zizaco/entrust": "dev-laravel-5",
        "spatie/activitylog": "^2.1",
        "felixkiss/uniquewith-validator": "2.*",
        "intervention/image": "^2.3",
        "barryvdh/laravel-dompdf": "^0.6.0",
        "maatwebsite/excel": "^2.0",
        "cviebrock/image-validator": "2.0.*@beta",
        "twilio/sdk": "^4.5",
        "guzzlehttp/guzzle": "^6.1",
        "elibyy/laravel-tcpdf": "0.*"   /* =====> TCPDF  */
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1"
    },
    "autoload": {
        "classmap": [
            "database"            
        ],
        "psr-4": {
            "App\\": "app/"
        },
        "files": ["app/Http/helpers.php"]
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "pre-update-cmd": [
            "php artisan clear-compiled"
        ],
        "post-update-cmd": [
            "php artisan optimize"
        ],
        "post-root-package-install": [
            "php -r \"copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    }
}

Thanks in Advance.



via Chebli Mohamed

Delivering content based on selects

I am slightly confused because I am not sure if I need models for this as I am not posting anything to a database. I have a simple index page

Route::get('/', 'IndexController@index');

Nothing special here. But on this index page I have four panels which take the following form

<a href="#" data-toggle="modal" data-target="#reportOneModal">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">Report One</h3>
        </div>
        <div class="panel-body"><img src="/images/image1.png"></div>
    </div>
</a>

When one of the panels is clicked, it brings up a modal with some select inputs. This is to filter out the report I need to display. Each panel has different options for the select inputs.

What I essentially need to do is post the selected inputs to my controller so I can figure out which image to display. A modal looks like this

<div class="modal fade" id="reportOneModal" role="dialog" aria-labelledby="reportOneModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-body">
                {!! Form::open(array('route' => array('report'))) !!}
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                {!! Form::label('productType', 'Report Type', array('class' => 'col-sm-5 control-label blue')) !!}
                                <div class="col-sm-7">
                                    <select class="selectpicker" name="reportType" id="reportType">
                                        <option value=""></option>
                                        <option value="Value">Value</option>
                                        <option value="Value">Salary</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row" id="yearRow">
                        <div class="col-md-12">
                            <div class="form-group">
                                {!! Form::label('reportYear', 'Year', array('class' => 'col-sm-5 control-label blue')) !!}
                                <div class="col-sm-7">
                                    <select class="selectpicker" name="reportYear" id="reportYear">
                                        <option value=""></option>
                                        <option value="2016">2015</option>
                                        <option value="2016">2016</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    {!! Form::submit('View Report', ['class' => 'btn btn-primary loadBtn']) !!}
                </div>
                {!! Form::close() !!}
            </div>
        </div>
    </div>
</div>

So you can see that the form for the modal is posting to report, I will call a different function for each panel. This route looks like this

Route::post('report', array('as' => 'report', 'uses' => 'IndexController@getReport'));

And the controller function is as follows

public function getReport()
{
    $reportType =  Input::get('reportType');
    $reportYear =  Input::get('reportYear');

    $filePath = 'report-images/' . $reportType . '/' . $reportYear . '/';
    $image = $reportType . '_' . $reportYear;
    $fullPath = $filePath . $image . '.png';

    if(!empty($fullPath)) {
        return view('report.report', compact('fullPath'));
    }
}

The problem I am having refers to one report I am trying to display. I can display the image fine, but there are many different variants to this image. So on this reports view I have added

<select class="selectpicker" name="bmId" id="bmId">
    <option value="variant1">variant1</option>
    <option value="variant2">variant2</option>
    <option value="variant3">variant3</option>
</select>

When one of these variants are selected, I need to somehow recall the route report.getReport2. I presume I could do this with ajax, at the moment I am trying

$("#bmId").change(function() {
    $.ajax({ url: "test.html", context: document.body, success: function(){
        $(this).addClass("done");
    }});
});

The problem is, I do not want to call a url, I want to call the route and pass it this new variant value.

How would I go about doing something like this?

Thanks



via Chebli Mohamed

NotFoundHttpException in RouteCollection.php line 161.

Am trying to create a login form using 'http://localhost/myproject/public/auth/login' but i keep getting that error. Below is my routes.php :

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

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

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

I have also create resources\views\auth\login.blade.php file. Can anyone please help since i'm following Laravel 5.1 on this but can't quite know whats wrong.



via Chebli Mohamed

lundi 18 juillet 2016

Search Food Items in laravel

I have a search box in my views and I want to search foods from the database. My view for seach box is:

<div class="field" id="searchform">

<input type="text" id="searchterm" placeholder="e.g mutton 

karahi,pizza..."  />

<button type="button" id="search" 

onclick="window.location='http://localhost:8000/search'">Find Food!</button>

</div>

My food table has fields like:

  1. Food_id
  2. FoodName
  3. FoodDescription
  4. FoodImage
  5. Price

Now I want to search my foods By name.How I can do that?plz help me.I am new to laravel and I am using laravel 5.2.



via Chebli Mohamed

Laravel 5.1 Call to undefined method Illuminate\Support\Facades\Request::cookie()

I'm trying to load the value of a cookie in a controller in Laravel 5.1, but I'm getting this error:

FatalErrorException in SurveyController.php line 21: Call to undefined method Illuminate\Support\Facades\Request::cookie()

Here is my code:

<?php

namespace App\Http\Controllers;
use Response;
use Request;
use Illuminate\Routing\Controller;
use Cookie;
use Log;

class SurveyController extends Controller {

    /**
     * Index method. Decide to resume a survey or start a new one.
     */
    public function index(Request $request) {

        dd($request->cookie('survey_id'));
    }
}

From what I can tell from the documents, this appears to be the correct way to load a cookie value. What am I doing wrong?



via Chebli Mohamed

subquery in laravel - wich()

I'm making a query using the following line:

$items = $this->model->with('subCategory')->get();

But I want to put a query inside the with() method, because I just want to get the items from with() where the status is equal to 0.

How can i achieve this?



via Chebli Mohamed

Why Laravel Pagination stuck at page 1?

I have a very simple Laravel application. Basically I'm using Eloquent to pull out data from the DB and paginate them.

However it's not working properly. Every time I'm using the paginate command I'm getting the first page's result only.

Here's my code:

$forum = new Forum;
$posts = $forum->paginate(5);
return $posts;

What I'm getting back as JSON is:

total: 33,
per_page: 5,
current_page: 1,
last_page: 7,
next_page_url: "http://ift.tt/29J1etJ",
prev_page_url: null,
from: 1,
to: 5,

... and the first 5 results.

When I click to the next page URL it's loading the exact same first page results and I have the exact same response:

total: 33,
per_page: 5,
current_page: 1,
last_page: 7,
next_page_url: "http://ift.tt/29J1etJ",
prev_page_url: null,
from: 1,
to: 5,

...with the same 5 first posts.

I haven't changed any settings in Laravel and I'm using Laravel 5.2.

Can anyone tell me what am I missing here?



via Chebli Mohamed

Get all data from pivot table

By now, I can get the data in the pivot table, but my question is, how can I get all the categories from my categories table and, if exists this category in my pivot table the input needs to be checked, how can I get this?

Project model

class Project extends Model
{
    protected $table = 'projects';

    protected $fillable = [
        'name',
        'slug',
        'header',
        'desc',
        'about',
        'url',
        'status'
    ];

    public function customer()
    {
        return $this->belongsTo(Customer::class);
    }

    public function category()
    {
        return $this->belongsToMany(Category::class)->withPivot('category_id');
    }
}

Category model

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

    protected $fillable = [
        'name',
        'status'
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function subCategory()
    {
        return $this->hasMany(SubCategory::class);
    }

    public function projects()
    {
        return $this->belongsToMany(Project::class)->withPivot('project_id');
    }
}

Controller

public function getEdit(Customer $customer, $project)
{
    return view('admin.pages.admin.clientes.projetos.edit', [
        'customer' => $customer,
        'project' => Project::where('id', $project)->firstOrFail(),
        'categories' => $this->categoryRepository->allCategories(), //return all categories in the categories table
        'title' => $customer->name
    ]);
}

Form

{!! Form::model($project, ['class' => 's-form', 'route' => ['project.update', $customer->id, $project->id]]) !!}
    
    <div class="s-form-item text">
        <div class="item-title required">Nome do projeto</div>
        {!! Form::text('name', null, ['placeholder' => 'Nome do projeto']) !!}
        @if($errors->has('name'))
            <div class="item-desc"></div>
        @endif
    </div>
    <div class="s-form-item text">
        <div class="item-title">Descrição do projeto</div>
        {!! Form::text('desc', null, ['placeholder' => 'Descrição do projeto']) !!}
        @if($errors->has('desc'))
            <div class="item-desc"></div>
        @endif
    </div>
    <div class="s-form-item text">
        <div class="item-title">Sobre o projeto</div>
        {!! Form::text('about', null, ['placeholder' => 'Sobre o projeto']) !!}
        @if($errors->has('about'))
            <div class="item-desc"></div>
        @endif
    </div>
    <div class="s-form-item text">
        <div class="item-title">URL do projeto</div>
        {!! Form::text('url', null, ['placeholder' => 'URL do projeto']) !!}
        @if($errors->has('url'))
            <div class="item-desc"></div>
        @endif
    </div>
    <div class="s-form-item text">
        <div class="item-title">Imagem de cabeçalho do projeto</div>
        {!! Form::text('header', null, ['placeholder' => 'Imagem de cabeçalho do projeto']) !!}
        @if($errors->has('header'))
            <div class="item-desc"></div>
        @endif
    </div>
    <div class="s-form-item checkbox inline">
        <div class="item-title">Categorias do projeto</div>
        @foreach($project->category as $category)
            
            
                " type="checkbox" name="categories[]" value="">--}}
                "><span></span></label>--}}
            
        @endforeach
    </div>
    <div class="s-form-item radio inline">
        <div class="item-title required">Status do projeto</div>
        <div class="s-radio-input">
            {!! Form::radio('status', '1', null, ['id' => 'categoria-ativo']) !!}
            <label for="categoria-ativo"><span></span>Ativa</label>
        </div>
        <div class="s-radio-input">
            {!! Form::radio('status', '0', null, ['id' => 'categoria-inativo']) !!}
            <label for="categoria-inativo"><span></span>Inativa</label>
        </div>
    </div>
    <div class="s-form-item s-btn-group s-btns-right">
        <a href="" class="s-btn cancel">Voltar</a>
        <input class="s-btn" type="submit" value="Atualizar">
    </div>
{!! Form::close() !!}



via Chebli Mohamed

How to store the relation between tables

I created a table in relation to two other tables, however I do not know how to relate them when creating new projects, how could I do that?

I'll create the categories in a separated page in my admin, and when the user create's a new project he will be able to select an array of categories coming from the table.

My question is, how can I store the relation when POST the data? I've never done this before.

Project model

class Project extends Model
{
    protected $table = 'projects';

    protected $fillable = [
        'name',
        'slug',
        'header',
        'desc',
        'about',
        'url',
        'status'
    ];

    public function customer()
    {
        return $this->belongsTo(Customer::class);
    }

    public function category()
    {
        return $this->belongsToMany(Category::class);
    }

    public function categories()
    {
        return $this->hasMany(Category::class);
    }
}

Category model

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

    protected $fillable = [
        'name',
        'status'
    ];

    public function subCategory()
    {
        return $this->hasMany(SubCategory::class);
    }

    public function projects()
    {
        return $this->belongsToMany(Project::class);
    }
}

My actual Post create

public function postCreate(ProjectCreateRequest $request, Customer $customer)
{

    //Array
    $categories = $request->categories;

    $customer->projects()->create([
        'name' => $request->name,
        'header' => $request->header,
        'desc' => $request->desc,
        'about' => $request->about,
        'url' => $request->url,
    ]);

    //How do I store the relation?

    return redirect('admin/clientes/editar/' . $customer->id);
}



via Chebli Mohamed

InvalidArgumentException in FileViewFinder.php line 137: View [books.edit] not found

I am getting error like InvalidArgumentException in FileViewFinder.php line 137: View [books.edit] not found my Routes Route::resource('books','BookController');
Route::get('books', 'BookController@index');
Route::get('books/edit/{id}', 'BookController@edit');

My View<br>

@extends('layout/template')

@section('content')
 <h1>BookStore</h1>
 <a href="" class="btn btn-success">Create Book</a>
 <hr>
 <table class="table table-striped table-bordered table-hover">
     <thead>
     <tr class="bg-info">
         <th>Id</th>
         <th>ISBN</th>
         <th>Title</th>
         <th>Author</th>
         <th>Publisher</th>
         <th>Thumbs</th>
         <th colspan="3" style="text-align: center;">Actions</th>
     </tr>
     </thead>
     <tbody>
     @foreach ($books as $book)
         <tr class="bg-info">
             <td></td>
             <td></td>
             <td></td>
             <td></td>
             <td></td>
             <td><img src="" height="35" width="30"></td>
             <td><a href="" class="btn btn-primary">Read</a></td>
             <td><a href="" class="btn btn-warning">Update</a></td>
             <td>
             {!! Form::open(['method' => 'DELETE', 'route'=>['books.destroy', $book->id]]) !!}
             {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
             {!! Form::close() !!}
             </td>
         </tr>
     @endforeach

     </tbody>

 </table>
@endsection


via Chebli Mohamed

Populating select options dynamically based on previous choices

I am having issues prepopulating select boxes based on an array. Now I am passing my view an array which looks like the following

array:4 [▼
  "folder1" => array:1 [▶]
  "folder2" => array:2 [▶]
  "folder3" => array:1 [▶]
  "folder4" => array:1 [▼
    "product1" => array:1 [▼
      2016 => array:1 [▼
        "March" => array:1 [▼
          0 => "image1.png"
        ]
      ]
    ]
    "product2" => array:1 [▼
      2015 => array:1 [▼
        "June" => array:1 [▼
          0 => "image1.png"
        ]
      ]
    ]
  ]
]

Now for this part I am only interested in folder4. I plan on having 4 select inputs. The first one should display the products. The products are folders within the root of folder4.

So in the example above, this select should show product1 and product2.

The second select should show the years. The years are folders within the products. The third select should show the months. The months are folders within the years folders.

The last select should show the image names.

All of this will probably need to be within the foreach loop. Reason I say this is because if they select product2 in the first select box, the next select box should only have the year 2015, not the year from product1 folder. This is where I am at this moment in time, but it is quite a way off

<select class="selectpicker" name="productType">
    @foreach($fileData as $type => $product)
        @if($type == "folder4")
            @foreach($product as $name => $year)
                <option value=""></option>
            @endforeach
        @endif
    @endforeach
</select>

At the moment I am getting htmlentities() expects parameter 1 to be string, array given. This select should display product1 and product2. Also, have do I make the other select options dynamic based on what has been previously chosen? So if they choose product 1, the next select box should display the year 2016 only.

Any advice appreciated.

Thanks



via Chebli Mohamed

Error using two or more customs service provider - Laravel 5.1

time ago I made a facade to handle emails called 'MyMailer'.

It works good, but now, I need to add a new facade that I called 'Message'.

I made the new facade such as I made the 'MyMailer' facade. Below I will copy the code:

App/Components/MyMailer.php

<?php

namespace App\Components;

use Mail;


class MyMailer{

    public function sendMailForAlert($email, $data, $message){

        Mail::send('emails.newData', ['data' =>$data],         function($message) use ($email){
            $message->to($email)
                ->subject('Sending data');
        });

    }


}

App/Facades/MyMailer.php

<?php

namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class MyMailer extends Facade {

    protected static function getFacadeAccessor()
    {
        return 'build';
    }
}

App/Providers/MyMailerServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class MyMailerServiceProvider extends ServiceProvider

{

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        \App::bind('build', function()
    {
        return new \App\Components\MyMailer;
    });
    }
}

App/Components/MyMessage.php

<?php

namespace App\Components;


use Illuminate\Http\Request;
use Exception;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class MyMessage{

    public function getMessage()
    {
        return 'hello';
    }
}

App/Facades/MyMessage.php

<?php

namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class MyMessage extends Facade {

    protected static function getFacadeAccessor()
    {
        return 'build';
    }
}

App/Providers/MyMessageServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class MyMessageServiceProvider extends ServiceProvider
{


    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        \App::bind('build', function()
        {
            return new \App\Components\MyMessage;
        });
    }
}

I had registrated the alias and service provider in config/app.php. The problem is that I get an error when I use a facade. Example:

<?php
namespace App\Http\Controllers\Example;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use MyMailer;

class ExampleController extends Controller
{

   public function executeExample(){

      MyMailer::sendMailForAlert('foo@bar.com', 'data', 'new data');


   }


}

I am getting this message: call_user_func_array() expects parameter 1 to be a valid callback, class 'App\Components\MyMessage' does not have a method 'sendMailForAlert'. I don't know why because I am not using 'MyMessage' facade.

Any help is welcome. Thank you



via Chebli Mohamed

dimanche 17 juillet 2016

Laravel :: Best way to update foreign key

I have this migration file

Schema::create('table_one', function(Blueprint $table) 
{ 
    $table->increments('id'); 
    $table->string('name'); 
    $table->integer('table_two_id')->unsigned(); 
    $table->foreign('table_two_id')->references('id')->on('table_two'); 
    $table->timestamps(); 
});

and I want to update to make it ->onDelete('cascade');

$table->foreign('table_two_id')->references('id')->on('table_two')->onDelete('cascade');

What is the best way to do this?

Is there something like ->change();

Thanks



via Chebli Mohamed

Get averages across multiple columns with GroupBy

I want to compile statistics on how users are answering questions for my app. I am using Laravel 5.1 for my API which will handle this.

I have x entries in my questions_user table, and want to first group by question_id, then get the averages per each group for user_timing, and other potential fields.

enter image description here

    $user_questions = DB::table('question_user')
        ->select('question_id', 'user_timing', DB::raw('count(*) as total'))
        ->groupBy('question_id')
        ->get();

Gets me:

[
 {
  "question_id": 1,
  "user_timing": "5",
  "total": 2
 },
 {
  "question_id": 2,
  "user_timing": "10",
  "total": 1
 },
 {
  "question_id": 3,
  "user_timing": "4",
  "total": 3
 }
]

If I add ->avg('user_timing') just before the get(), it gives error:

"Call to a member function get() on double"

I'm assuming this is because avg computes the value and returns it to the get(), which is expecting a query object.

if I add ->avg('user_timing') in place of get(), it returns a single value 4, which is not the average of anything, let alone groups.

How can I return aggregate values across multiple fields in multiple groups?



via Chebli Mohamed

xero api integration in php for a public type application (code conversion)

I want to integrate "XERO API" for public application in PHP. I stuck with Oauth application authorisation I have download code from GITHUB (find on "XERO API" code sample for public application) and i want to convert the public file code in to class PHP



via Chebli Mohamed

These credentials do not match our records. laravel 5.1

hi I'm using Laravel authentication. in my login form if i submit without filling fields i see an error that says the filed is required . but when i try to fill the form with wrong username and password it has to say "These credentials do not match our records." but it wont say
I'm using laravel 5.1



via Chebli Mohamed

samedi 16 juillet 2016

Unable to access object properties from URL params in Laravel

I am trying to access object properties from a request from my Angular app. I am using Laravel 5.1

Angular:

console.log('getQuestionAnswers', params);
return $http({
    method: 'GET',
    url: url + ver + '/questions/checkMany',
    params: {
        'questions[]' : params
    },
    headers: {
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + $rootScope.access_token
    },
    cache: true
});

Console.log of params:

enter image description here

Laravel:

public function getAnswers(Request $request)
{
    $input = $request->all();

    $question_objs = $input['questions'];

    foreach ($question_objs as $question_answer_object) {
        return $question_answer_object;

enter image description here

Looks like so far so good!


But if I try to access a property within laravel, like question_id:

return $question_answer_object['question_id'];

I get error:

"Illegal string offset 'question_id'

Laravel already parses the JSON, and when I return it, I can see it's an object. Why can't I access the properties? I've also tried json_decode without luck.



via Chebli Mohamed