mercredi 30 septembre 2015

Trying to install packages in Larave 5

I was trying to install the package of HOA/Websockets in my Laravel5 website ,

from following link

http://ift.tt/1OId7ki

But when I added the

"require": {
        "hoa/websocket": "~2.0"
    }

In my composer and ran

composer install 

But in my command promt it says nothing to be installed Can any one help me out with this ,

Please Also when I try to do

composer require "hoa/websocket": "~2.0"

it is uninstalling some of the packages and not installing it back

Thanks in advance



via Chebli Mohamed

UnexpectedValueException in Response.php line 403 - Laravel 5.1

I am new to Laravel and am building a small project as my schooling. I have struck the above error and I cannot seem to fix it. Any help is appreciated.

In my controller I make the following call when first loading the page. The getDetails method works perfectly on page load, but fails with above error when I call it with Ajax as the user interacts with the page after load.

On page load the method is called and passed to it resulting values from earlier other method calls ($CSpec[0]->id and $CSize[0]->size_mm, which I can see as values 1 and 0.5) as follows:

    $CD = CS::getDetails($CSpec[0]->id, $CSize[0]->size_mm);

Also in the controller I have the following function which triggered via a route used in an Ajax call:

public function itemDetails($ct, $cs)
{
    return CS::getDetails($ct, $s);
}

The getDetails method looks like this:

public static function getDetails($ct, $cs)
{
    return DB::table('recommend_view')
        ->where('recommend_view.id', '=', $ct)
        ->where('recommend_view.size_mm', '=', $cs)
        ->first();
}

I have this route:

Route::get('vd/cd/{cd}/{cs}',
        ['uses' => 'Application\VDController@itemDetails', 'as' => 'application.vdcdetails']);

When I use Ajax to call the same method it fails with the above error. The Ajax code produces the following url in the $.getJSON call:

http://ift.tt/1QM5Ddz

If I dd() inside getDetails for each variable I can see the correct values passed to the method from the url / controller.

So the method works perfectly when called on initial page load with variables fed to it directly from other method calls, but when the variables are passed via the URL / Ajax it fails and I cannot seem to understand what the difference is.

UnexpectedValueException in Response.php line 403:
The Response content must be a string or object implementing __toString(), "object" given.



via Chebli Mohamed

Transaction logs with large data processing in mysql

Don't know if I posted in the correct site. But here goes, Im having a problem with database transaction in processing large files. What my program do is I upload a csv file and in that file it can have up to 50,000 records. Right now it worked when I processed 200 rows but when I tried with 20,000 rows it never get to insert in my db (i saw the insertion sql in my logs but when i check it out it never entered). So I'm guessing that my buffer size for the transaction logs hit its limit.

I have this code in my laravel

try {
  DB::beginTransaction();
  process my logic (validation, log, etc..)
  DB::commit()
}catch() {
  log::error();
  DB::rollback;
}

I just added these two config in my /etc/mysql/my.cnf

[innodb]
innodb_buffer_pool_size = 128M
innodb_log_file_size    = 64M

I thought it would fix my problem but sadly not. Please help.



via Chebli Mohamed

Create using save() is causing database duplicates in Laravel

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

DonateController.php

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

Database Results (with test data) enter image description here

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

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

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

Right now, I'm accessing this method by pinging its route:

Route::get('/paypal/mimic', 'DonateController@mimic');

but for every 1 ping I make, I get 2 database entries as shown in the above image.

Thanks in advance for any help.



via Chebli Mohamed

Laravel - How to register custom broadcaster

I want to register a custom broadcaster with the BroadcastManager without having to change the internal framework code...

Now I have to do something like this in the Illuminate\Broadcasting\BroadcasterManager class:

protected function createMyCustomDriver(array $config) {
  // return instance....
}

There is an extend method however, but I don't know if it's ment for this use case or how to use it...

The goal is to use a Broadcaster implementation that uses ZMQ to send these broadcasted events to the WebSocket php server instance.

Any help appreciated!



via Chebli Mohamed

Weird Laravel 5 caching using wrong database name

I have two Laravel APIs that are serving an AngularJS app all on my local development machine. I'm getting a weird issue when the Angular page calls POSTs to both APIs where it seems to be using the wrong database name (it's using the other Laravel's instance's database). Laravel throws an exception that says Table database.table not found, where database is the incorrect database. I've tried calling each of the APIs using Postman and that works fine, and I'm sure there is no mention of the other database in either project.

To me this seems like a caching issue, where the .env file might be cached and shared between the two Laravel servers for some reason. Both of the Laravel apps are hosted on Apache. I've tried calling php artisan config:clear and have set the appropriate headers in the .htaccess files to try to prevent any caching but neither of those worked. I have also tried on multiple browsers, cleared the cache, and still the same error.

I want to be able to use the .env file so that I can have a unique configuration for my development server so I'd rather not hardcode the database credentials in config/database.php. Any ideas what could be the issue?

Both database.php files look like:

'mysql' => [
'driver'    => 'mysql',
'host'      => env('DB_HOST'),
'database'  => env('DB_DATABASE'),
'username'  => env('DB_USERNAME'),
'password'  => env('DB_PASSWORD'),
'charset'   => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix'    => '',
'strict'    => false, 
],

Where the unique settings are stored in .env



via Chebli Mohamed

How wherePivot() actually works internally in laravel 5?

How wherePivot() actually works internally in laravel 5 ?

For Example I was practicing by watching a tutorial and the teacher was using wherePivot() for construing relationship:

public function friendsOfMine(){

    return $this->belongsToMany('Chatty\Models\User','friends','user_id','friend_id');
}

public function friendOf(){

  return $this->belongsToMany('Chatty\Models\User','friends','friend_id','user_id');

}

public function friends(){

  return $this->friendsOfMine()->wherePivot('accepted',true)->get()->merge($this->friendOf()->wherePivot('accepted',true)->get());

} 



via Chebli Mohamed

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

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

@extends('layouts.master')

@section('content')

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

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

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

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

@endsection



via Chebli Mohamed

Laravel Behat fails when visiting back the same page

In the following Behat scenario the last statement failed, where "Raining" is seen, but expected not to see.

Scenario: Can update existing document
    Given there is an active user with email "johndoe@gmail.com" and name "John Doe"
    And the user with email "johndoe@gmail.com" has a document title "Raining"
    When I am logged in with email "johndoe@gmail.com"
    And I go to "/document"
    Then I should see "Raining"
    When I follow "Raining"
    Then I follow "Edit"
    Then I fill in "title" with "Rainbow"
    And I press "Save changes"
    Then I should be on "/document"
    And I should see "Document changes saved successfully"
    Then I should not see "Raining"

And I should see "Document changes saved successfully" passed.

But Then I should not see "Raining" failed.

When I print the output before that step which fails, I see the old value still there, with that success thinggy. Obviously that is not the case when I manually performed the steps with browser.

It seems the problem will occur whenever the steps involve visiting the same page.

Is this a known issue or workaround with this?



via Chebli Mohamed

Is there a more complete manual for larval 5.1?

I'm using larval for a project and it's a great framework, but the manual often falls short.

For example, I'm trying to figure out how to use named routes in the view using blade, but the manual explains how to declare them and how to use it in the backend but ends there. I'm pretty sure there's a way to generate a URL using the name of the route.

This isn't the only problem I've ran into where I can't get the whole story on the manual. Do you know of a place where I can read the more complete manual?



via Chebli Mohamed

Laravel auth problems

First problem is error when I'm using route without index.php: The requested URL /auth/login was not found on this server. I found that this error may appears when mod_rewrite isn't set, but it is.

Second problem is PDO error: PDOException in Connector.php line 50: SQLSTATE[HY000] [2005] Unknown MySQL server host 'localhost:3306' (2) I found that this may appear because DB_HOST is set 'localhost:3306' on PHP 5.5 and higher, but it's set 'localhost'



via Chebli Mohamed

How to validate an Input Array field in Laravel 5.1?

How can I write rule for input field like below:

{!! Form::number("amount[]",null,['min' => 0, 'class' => 'form-control col-xs-2 ']) !!}

I tried following which gave error: htmlentities() expects parameter 1 to be string, array given

        $rules = array(
            'amount[]' => 'required'
        );
        $this->validate($request, $rules);



via Chebli Mohamed

Laravel5.1 Route set all URL to Controller

I think get/post visit Controller

Route::match(['get','post']. '{Controller}/{method}','$Controller\$Controller_Controller@$method');

But this is error;

How to I localhos/website/User/login ,go to find Controllers/User/User_Controller@login?



via Chebli Mohamed

Laravel 5.1 utf-8 saving to database

I'm trying to save a record to database. When get value from input and save it to database there is no problem, like :

$request->input('name') is an input with value of 'سلام'

$provider->name = $request->input('name');
$provider->copyright_email = 'test@yahoo.com';
$provider->save();

But when i try give value from my controller problem appears. Name will save '?' into database :

$provider->name = 'سلام';
$provider->copyright_email = 'test@yahoo.com';
$provider->save();

I've already added this code to config/database.php :

'charset' => 'utf8',
'collation' => 'utf8_persian_ci',



via Chebli Mohamed

How to have a multi tenant database in laravel where every tenant has multiple users?

So I am trying to understand how a multi tenant database approach works but I am confused in some places. I am trying to use it in Laravel and MySQL

I understand that I can have a databases for each tenant in my application so when a user logs in, I can just check which tenant it is and change the DB connection to use their database. I am guessing this is how it works.

But now here is where I start to get confused. The tenant that logs into the application will be able to create users and assign them roles which means that there is super admin which creates all the tenants but then there is also a super admin for a particular tenant which will creates users for the instance of the tenant itself.

So now how will I authenticate users in such a situation. For example, I can authenticate a tenant and then change the DB connection to the appropriate database but then I will have to log in the user of that particular tenant and how will I keep two enitities logged in at the same time in the session?

I am guessing a multi auth package (like Multi Auth) might help in doing that but since I am new to this I am mostly blurry.

I am hopping someone has already encountered this problem and might be able to help me.



via Chebli Mohamed

Swift Mailer with queue in laravel 5 for console command

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



via Chebli Mohamed

Using rydurham Sentinel on specific route in Larvel 5.1

I am using sentinel by Ryan Durham http://ift.tt/MSeZd7 with Laravel 5.1.

I used to use Confide http://ift.tt/XgMzel with Larvel 4.2.

With Confide I was able to add an auth to any route like this

// Applies auth filter to the routes within orders/ 
Route::when('orders/*', 'auth');

I've searched through Sentinel documentation for this feature but I cannot find out how to get this done. I can put an auth for say admin or user in the construct of a controller, but I need to have specific auth abilities on specific routes.

My question is, how can I redirect a user who goes to a route only for admin using rydurham sentinel in a clean fashion the same as Confide?



via Chebli Mohamed

mardi 29 septembre 2015

Are polymorphic relationships bad practice?

I'm using Laravel and have run into the need to have something just like polymorphic relationships. It would seem that they solve exactly what I need, which is being able to store different data based on a type, in a nutshell.

However, I'm aware that I would not be able to use any constraints, like foreign keys. And I've read around that they're essentially an anti-pattern. But I was wondering what others think about it, and if anyone is using them without issues.

Otherwise, is there an alternative way I could accomplish what polymorphic relationships provide, without actually using them? (Using Laravel)



via Chebli Mohamed

Laravel check if there is any data stored for the upcomming hour

I want to check if there is any data stored in mysql for the upcoming hour. I am using laravel 5.1 and carbon to store and get data.

Here is my code:

 * Check if there is any data for the upcoming hour
 *
 * @return \Illuminate\Http\Response
 */
public function test()
{
    $timestamp = Carbon::now('Australia/Brisbane');

    // start time with end time check in between
   $post = DB::table('posts')
                ->join('profiles', 'posts.profile_id', '=', 'profiles.id')
                ->where('posts.scheduled_time', '=', $timestamp->addMinutes(59)->toDateTimeString())
                ->get();
   dd($post);

}

When I run the query I just get an empty array. Im not sure what I've missed.



via Chebli Mohamed

Strange behavior in Laravel queue job

Please consider the following job:

<?php

namespace App\Jobs;

use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ImportUsers extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

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

    public function handle()
    {
        dd($this->number);
        return;
    }
}

Dispatching this job using a sync queue $this->dispatch(new \App\Jobs\ImportUsers(5)); throw this exception: Undefined property: App\Jobs\ImportUsers::$number. This really seems odd for me. Why the handle method can not access class properties?



via Chebli Mohamed

how to fix $PATH in Virtual Box Ubuntu 14.04 after npm global install

I've been trying to install npm globally in virtual box with ubuntu 14.04 and Apache 2.4 with various problems with Laravel 5.1

Reading through the docs on npm adn following through these instructions http://ift.tt/1Arp6KO I know I have completed wrecked my $PATH

Previously when I ran echo $PATH I got something like this;

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/games

Now when I echo $PATH I get the following;

/usr/local/bin:/bin

I have managed to stuff everything up on my Laravel install, composer no longer works, php artisan no longer works - am just wondering if anyone is able to help me get back to where I was...



via Chebli Mohamed

Binding not supported in Eloquent 5.1?

I'm new to Laravel and trying to do a string query in Eloquent. I was trying to use DB::statement, but I kept getting errors about placeholders in the query string. It seems I either don't have the syntax right, or bindings are unimplemented or unsupported?

The reason I want to use statement is because I'm doing an INSERT... SELECT, which I haven't been able to find any documentation about in Eloquent.

Here's my code:

$ php artisan tinker
Psy Shell v0.5.2 (PHP 5.6.13-0+deb8u1 — cli) by Justin Hileman
>>> echo \DB::statement('CREATE DATABASE :db', [':db'=>'test']);
Illuminate\Database\QueryException with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1 (SQL: CREATE DATABASE :db)'
>>> \DB::statement('CREATE DATABASE ?', ['test']);
Illuminate\Database\QueryException with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1 (SQL: CREATE DATABASE test)'

These are the two syntax forms (? and :string) from PDO. Other methods in DB such as select and insert support this, according to the documentation.

This question on Laracasts is asking about the syntax, but there is no accepted answer.



via Chebli Mohamed

Organize routes and sub-routes in legal app using Laravel

I'm working in legal web app using Laravel 5, and I have 11 classes 'models' and they are working fine.

In the real world there are lawyers working in different offices, each office had one admin can create or open cases or 'lawsuits' for litigants, and the lawyers follow and update those cases in the courts or when they back to offices.

the problem that I was confuse how to sort them in my route and sub-routes ..

How do I have to sort them starting from the lawsuits, litigants or lawyers ?

A)

  • offices -> lawyers -> lawsuits -> sessions -> judgments
  • offices -> lawyers -> lawsuits -> litigants
  • offices -> meetings
  • articles
  • courts
  • judges
  • users

B)

  • offices -> lawsuits -> sessions -> judgments
  • offices -> lawsuits -> litigants
  • offices -> lawsuits -> lawyers
  • offices -> meetings
  • articles
  • courts
  • judges
  • users

C)

  • offices -> litigants -> lawsuits -> sessions -> judgments
  • offices -> litigants -> lawsuits -> lawyers
  • offices -> meetings
  • articles
  • courts
  • judges
  • users

or I have to create them all? or something else I don't know about ? is there "right way" to sort it?



via Chebli Mohamed

Laravel Authorization for Eloquent collection

How to apply laravel Gate (http://ift.tt/1hOo5aK) for an eloquent collection.

It works for single item like below

$post = Post::findOrFail($id);

if ($user->cannot('view-post', $post)) {
   abort(403);
}

But not working for a collection. Is it possible to filter the collection using Gate and return a collection?

$posts = Post::all();



via Chebli Mohamed

Laravel UNION ALL not working with where statement

I want to get two queues to one.

$buildings_queue=IngameBuildingQueue::where(DB::raw('UNIX_TIMESTAMP(`start_time` + `duration`)'),'<=',time());
$recruit_queue=IngameRecruitQueue::where(DB::raw('UNIX_TIMESTAMP(`start_time` + `duration`)'),'<=',time());
$queue=$buildings_queue->unionAll($recruit_queue);
dd($queue->toSql());

Laravel throw [ErrorException] Undefined property: Illuminate\Database\Eloquent\Builder::$bindings but when I delete where() methods everything works fine.

How can I fix it?



via Chebli Mohamed

How to get username from articles in Laravel 5?

Let's say each article is related with a user by holding a user_id value that is a foreign key to the id field in the users table.

And we defined the user method inside Article model with $this->belongsTo('App\User'), and the article method inside User model with $this->hasMany('App\Article').

What is the proper way to get the articles along with the username of the creator, in order to use them in the view?



via Chebli Mohamed

Laravel 5.1 - Need help to convert Raw Query to Eloquent

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

Raw Query:

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



via Chebli Mohamed

helper for links to next and previous records - laravel

When learning the basics of Laravel I implemented this tip

Laravel Quick Tip – get previous / next records

to make "go to next/previous records.

    // get next user id
    $next = Model::where('id', '>', $object->id)->min('id');
    $next = Model::find($next);

and then in my view file:

<a href="{{ URL::to(  'models/' . join('-', [$next->id, $next->slug]) ) }}" class="ui button nav">

GO TO NEXT

I have put this code into all controllers with show() action. It works, but it doesn't look as a good practice.

My question:

Can we make a helper for these links, please?

Peter



via Chebli Mohamed

How to select year and month from the created_at attributes of database table in laravel 5.1?

My problem is that I want to get data form the database table from the created_at attributes as per year and month only. The code I have tried is:

$post= Mjblog::select(DB::raw('YEAR(created_at) year, MONTH(created_at) month'));
$posts_by_y_m = $post->where('created_at',$post)->get();



via Chebli Mohamed

How to create sub folders using pingpong package in laravel 5.1

I am developing modular project in laravel 5.1 using pingpong package.Which gives me the project structure as below.

laravel-app/
    app/
    bootstrap/
    vendor/
    modules/
      ├── Blog/
          ├── Assets/
          ├── Config/
          ├── Console/
          ├── Database/
              ├── Migrations/
              ├── Seeders/
          ├── Entities/
          ├── Http/
              ├── Controllers/
              ├── Middleware/
              ├── Requests/
              ├── routes.php
          ├── Providers/
              ├── BlogServiceProvider.php
          ├── Resources/
              ├── lang/
              ├── views/
          ├── Repositories/
          ├── Tests/
          ├── composer.json
          ├── module.json
          ├── start.php

I want to seperate this modules forlders in "admin" and "client" for differenciate my client and admin side like below,

laravel-app/
    app/
    bootstrap/
    vendor/
    modules/
      ├── Admin/
          ├── Blog/
              ├── Assets/
              ├── Config/
              ├── Console/
              ├── Database/
                  ├── Migrations/
                  ├── Seeders/
             ├── Entities/
             ├── Http/
                  ├── Controllers/
                  ├── Middleware/
                  ├── Requests/
                  ├── routes.php
             ├── Providers/
                 ├── BlogServiceProvider.php
             ├── Resources/
                 ├── lang/
                 ├── views/
             ├── Repositories/
             ├── Tests/
             ├── composer.json
             ├── module.json
             ├── start.php
      ├── Client/
          ├── Blog/
              ├── Assets/
              ├── Config/
              ├── Console/
              ├── Database/
                  ├── Migrations/
                  ├── Seeders/
             ├── Entities/
             ├── Http/
                  ├── Controllers/
                  ├── Middleware/
                  ├── Requests/
                  ├── routes.php
             ├── Providers/
                 ├── BlogServiceProvider.php
             ├── Resources/
                 ├── lang/
                 ├── views/
             ├── Repositories/
             ├── Tests/
             ├── composer.json
             ├── module.json
             ├── start.php

please help me out for this, Thanks.



via Chebli Mohamed

laravel5.1 sort method not working

I am using laravel and have a problem with this code $item=User:find($id_code)->items; //retrieving items of a user $item=$item->sortBy("price");//the returned value is not sorted at all.

waiting for you help



via Chebli Mohamed

Laravel 5.1 Accessing Collection key / value

In Laravel 5.1 (PHP), I have a call as follows:

$CableSizes = CableType::getCableSizeList(1);

Which returns the following collection (as I understand). To show its contents I run dd($CableSizes);:

array:21 [▼
  0 => {#208 ▼
    +"cable_specification_id": 1
    +"cable_conductor_size_mm": "0.50"
  }
  1 => {#209 ▶}
  2 => {#210 ▶}
  3 => {#211 ▶}
  4 => {#212 ▶}
  5 => {#213 ▶}
  6 => {#214 ▶}
]

I can access the first element by doing dd($CableSizes[0]);. Ho do I access the contents on the first element, and retrieve cable_conductor_size or 0.50 in the example above). I am trying variations of dd($CableSizes[0].cable_conductor_size); but all returning errors.

I cannot seem to ask this question to Google so I get an example to view. How do I access this value?

Many thanks!



via Chebli Mohamed

lundi 28 septembre 2015

Command bus not going asynchronous

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

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

My code

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

Am i missing something? Please help.



via Chebli Mohamed

TCPDF Laravel Email Attachments

TCPDF doesn't seem to be working well with either $dest option ("E" or "S") for sending PDF attachments in Laravel 5.1. Files are always corrupt with an error upon launching Acrobat Reader (error message: ... for example, it was sent as an email attachment and wasn't correctly decoded). Decoding seems ok when I try another PDF generator like DOMPDF.

$pdf = new \TCPDF('P', 'in', 'LETTER', true, 'UTF-8', false);
$pdf->WriteHTML(view('emails.receipt_pdf', $receipt_data));
$attachment = $pdf->Output('Receipt - '.date("M-d-Y").'.pdf','E');

Mail::queue('emails.receipt_email', $receipt_data, function($message) use ($email, $attachment)
{
  $message->from('no-reply@website.com')
    ->to($email)
    ->subject('Receipt')
    ->attachData($attachment, 'Receipt.pdf');
});



via Chebli Mohamed

Laravel sessions and error log files are enormous

I noticed something recently that has me a little concerned and at a loss for an explanation. Last week I spun up an EC2 instance running Ubuntu 14.04 to start working on a new Laravel app.

Today, I noticed it was taking an unusually long time to sync. I noticed that my sessions folder was close to 1 gig and my log file was over 300 Mb. The log file was full of Token Mismatch Exceptions. Does anybody have any ideas on why this is happening?



via Chebli Mohamed

Laravel SQL Chunk gives -902: Error reading data from the connection

I'm currently querying a huge Firebird (v2.5) table (with millions of rows) in order to perform some row-level operations. To achieve that, the code is using chunking from Laravel 5.1, somewhat like this:

DB::connection('USER_DB')
    ->table($table->name)
    ->chunk(min(5000, floor(65500/count($table->fields))), function($data) {
        // running code and saving
    });

For some reason, I keep receiving the following error:

SQLSTATE[HY000]: General error: -902 Error reading data from the connection.

I've already tried changing chunk size, and different codes, but the error still appears. Sometime it happens at the beginning of the table, and sometimes after parsing several hundred-thousands or even millions rows. The thing is that I need to parse only the rows in this transaction (so I can't stop and reopen the script).

Tested for memory on the server (running on different place than the database), and it is not using nearly anything of it.

While writing this, I rechecked the Firebird log and found the following entry:

INET/inet_error: read errno = 10054

As far as I could find, this isn't actually a Firebird problem, but a winsock reset error, is that correct? If so, how could I prevent this from happening during the chunk query? And how can I check if that is a problem with windows or the firewall?

Update I

Digging on the firebird2.5.log on the PHP server, found this errors:

INET/inet_error: send errno = 104

REMOTE INTERFACE/gds__detach: Unsuccesful detach from database.



via Chebli Mohamed

Go back url Laravel 5.2

How can I get the previus url visited on the website in Laravel 5.1?

In Laravel 4 I just neede to write like

{{ URL::previous() }}



via Chebli Mohamed

PHPWord template: change the search-pattern

I'm using PHPWord for reading a Word template with strings that must be replaced with other values. PHPWord has the TemplateProcessor class, which is exactly what i need, but i need to change the search pattern used by default, which is

${search-pattern} 

I have tried changing the code in TemplateProcessor but it doesn't work. How can i change the search pattern used by PHPWord? Thanks!



via Chebli Mohamed

Alternatives of Join in MongoDB

I am new in mongoDB. I am facing Problem with mongoDB. That is "How do i give relationship between two collections in mongoDB?"

I read manual of mongoDB that mention mongoDB is not a RDBMS and mongoDB is not support Any kind of JOINS. But i want to know Alternatives of JOINS in mongoDB.



via Chebli Mohamed

dimanche 27 septembre 2015

laravel form model binding with has many through relationship

I wont use form model binding, and it's ok with simple models and one to one or has many relationships, but when use with has many through relationship have no effect. Is it possible? how correct handle?

Model

{!! Form::label('targeting_geo', trans('campaigns.targetingGeo') . ':', ['class' => 'control-label col-md-3']) !!}
{!! Form::select('targetingGeo[]', $targetingGeo, null, ['class' => 'form-control', 'multiple' => 'multiple']) !!}

Relation

    public function targetingGeo ()
{
    return $this->hasManyThrough(
        'App\Models\DictionariesCampaignTargetingGeo',
        'App\Models\CampaignTargetingGeo',
        'campaign_id',
        'id'
    );
}



via Chebli Mohamed

Eloquent insert multiple records into related model

I'm dealing with four different tables. users, activity, feeds and friends.

friends is the table where two foreign keys exist from users table (user_id and friend_id).

activity is the table where certain activities are hold.

feeds is the table that has two foreign keys, subscriber_id (the user's friend's id) and activity_id. When a user posts something, I want to insert records into feeds table to his friends will see his status updates. I hope it's clear so far. So there will be 20 inserts if there are 20 friends of a user.

Of course, I could do something like below, but that's not the "Laravel way".

    $friends = Auth::user()->friends;
    foreach ($friends as $friend) {
        $feed = new Feed;
        $feed->subscriber_id = $friend->id;
        $feed->activity_id = $status->id;
        $feed->save();
    }

friends relation in the User model.

public function friends() {
    return $this->belongsToMany('App\Models\User', 'friends', 'user_id', 'friend_id');
}

Insert in the controller

$status = new Activity;
$status->user_id = Auth::user()->id;
$status->status = Request::input("text");
$status->activity_type_id = 1;
$result = $status->save(); // OK, status is saved now.

if($result) {
  // insert data into feeds table
   $feed = new Feed;
   $feed->subscriber_id = Auth::user()->friends;
   $feed->activity_id = $status->id;
   $feed->save();
}

It gives exception.

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`testdatabase`.`feeds`, CONSTRAINT `feeds_ibfk_1` FOREIGN KEY (`subscriber_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into `feeds` (`subscriber_id`, `activity_id`, `updated_at`, `created_at`)



via Chebli Mohamed

Redirect after sending password reset link in Laravel 5.1?

How can set a redirect path after sending the password reset link?

In the ResetsPaswords trait is this code:

switch ($response) {
    case Password::RESET_LINK_SENT:
       return redirect()->back()->with('status', trans($response));

    case Password::INVALID_USER:
       return redirect()->back()->withErrors(['email' => trans($response)]);
}

But I don't want to change the vendor files. Is there another way?



via Chebli Mohamed

Laravel + WebSockets (Ratchet) Session

I have this working: http://ift.tt/1eEnl4v

But I'm not clear on how to check permissions on a user before allowing them to subscribe to a particular channel. I can see the laravel_session cookie in the request, but I don't know how or where to build the session object.

I'm happy to use file or database-based permissions. I'm open to memcache or redis, but I've never tried those before.



via Chebli Mohamed

laravel Call to a member function welcome() on null

i want to send mail so i made up a mail class so i can pass user data to send him mail. here is my code class Mailer.php

<?php 
use Mail;
abstract class Mailer{
public function sendTo($user, $subject,$view, $data = [])
{
    Mail::send($view, $data, function($message)
    {
        $message->to($user->email, $user->firstname) 
            ->subject($subject)
            ->from('test@test.com', 'Test');
    });
}
}

my class that extend the Mailer class :

class UserMailer extends Mailer{

public function welcome(User $user){
    $view = 'emails.welcome';
    $data = [];
    $subject = 'test subject';
    return $this->sendTo($user, $subject, $view, $data);
}

i want to call this class from any controller so i can pass user data to send mail but i always got this error Call to a member function welcome() on null : maybe i'm doing something wrong :

use App\UserMailer as Mailer ;

class TestController extends Controller
{
protected $mailer;
public function __construct(Mailer $mailer)
{
    $this->mailer;
}
public function testMailer()
{
    $this->mailer->welcome()->sendTo(1);
    return 'done';
}

I want to send this to user id 1. what is wrong with my code ? thx



via Chebli Mohamed

Change the public folder of Laravel 5.1

I was looking for a way to change the public's folder name in laravel 5.1, since my host only allos me to use a htdocs folder.



via Chebli Mohamed

samedi 26 septembre 2015

Laravel 5.1 installation - white screen and no .env file

I have a problem setting up Laravel 5.1 on my iMac with OS X Yosemite 10.10.5.

It's the first time I try to set it up on a Mac. Normally I use Windows and never had a problem. I have no problems with oder websites I have created, with or without vhosts.

I use the built-in apache2 server with php enabled and mysql installed. I modified my httpd.conf in order to be able to use the /Users/Fabian/Sites folder for my sites. I also created a virtual-host pointing to /Users/Fabian/Sites/Laravel/public.

At first, I installed composer globally. Next step was to install Laravel by:

cd /Users/Fabian/Sites
composer create-project laravel/laravel Laravel

So the download started and finished without any errors.

But now, my .env file is missing. I went to Github and copied the example-.env file from laravel/laravel repository. Now it looks like this:

APP_ENV=local
APP_DEBUG=true
APP_KEY=

DB_HOST=127.0.0.1
DB_DATABASE=junperbo
DB_USERNAME=root
DB_PASSWORD=

CACHE_DRIVER=file
SESSION_DRIVER=file

I have no app_key.

When I try to enter the Site via http://laravel.me I only get a white screen. There is nothing. No errors. Not even a source-code. laravel.me is my vhost pointing to /Users/Fabian/Sites/Laravel/public. And yes, it is set up in my /etc/hosts file ;)

Any ideas what went wrong during installation? Is there something I have to do in a different way on a Mac? I did the installation without sudo.

Thanks!



via Chebli Mohamed

How to find current route in larave 5.1?

I am using Laravel 5.1 , how I can find my current address Route?

{{ URL::current() }}

but i want find only route address?



via Chebli Mohamed

Laravel 5.1 Eloquent: How to retrieve a collection based on some conditions?

I need to filter a collection of projects based on some conditions. Hear is the scenario.

//This is part of projects table schema
  Schema::create('projects', function (Blueprint $table) {
           ...
            $table->smallInteger('source_lang_id')->index()->unsigned();
            $table->smallInteger('target_lang_id')->index()->unsigned();
           ...
        });
//This is part of translator_infos schema
Schema::create('translator_infos', function (Blueprint $table) {
          ....
            $table->smallInteger('from_l_1_id')->index()->unsigned();
            $table->smallInteger('from_l_2_id')->index()->nullable()->unsigned();
            $table->smallInteger('from_l_3_id')->index()->nullable()->unsigned();
            $table->smallInteger('from_l_4_id')->index()->nullable()->unsigned();
            $table->smallInteger('to_l_1_id')->index()->unsigned();
            $table->smallInteger('to_l_2_id')->index()->nullable()->unsigned();
            $table->smallInteger('to_l_3_id')->index()->nullable()->unsigned();
            $table->smallInteger('to_l_4_id')->index()->nullable()->unsigned();
        ....
        });

So each project has a source and target language. Translators may have 4 language pairs. What I need is that to filter the collection of projects and find projects that their source and target language match at least one of the translator language pairs and pass this collection to the view. For now the query I'm using is the following:

$projects=Project::orderBy('created_at', 'desc')->where('status_id', "=", 1)->paginate(15);

How can I add this condition to the query?



via Chebli Mohamed

Upload files using CKeditor

I am using ckeditor and I am trying to upload file. This is my code:

    @extends('app')
@section('header')
<script type="text/javascript" src="{{url('ckeditor/ckeditor.js')}}"></script>
@endsection
@section('content')
<div class="container">

    @include('common.errors')
<div class="row">
                <div class="col-lg-12">

                            <div class="row">
                                <div class="col-lg-9">
    {!! Form::model($info, ['route' => ['infos.update', $info->id], 'method' => 'patch','files' => true]) !!}

        @include('infos.fields')

    {!! Form::close() !!}
    </div>
    </div>
    </div>
    </div>
</div>
@endsection
@section('footer')
<script type="text/javascript">
    CKEDITOR.replace('editor1',{

        filebrowserImageUploadUrl : "{{route('infos.upload')}}",
        filebrowserWindowWidth  : 800,
        filebrowserWindowHeight : 500
    });
    window.opener.CKEDITOR.tools.callFunction(CKEditorFuncNum,url);
</script>
@endsection

Whenever I try to upload file, I get token mismatch error. The form builder automatically adds a hidden csrf field in the main form but since the file upload(POST request) from ckeditor happens through ajax it is giving me that error. I know that I can disable this error but when I googled I found out that it was a bad practise to disable it. How can I stop getting this error and upload files?



via Chebli Mohamed

2 small questions regarding larvael facades

I know it's an issue with a lot of debate, but there are two issues about it that I haven't seen much reference to and would like to know the answers to:

  1. We're using static functions all the time - I'm sure no one will ever stop using dd() helper for example, but obviously even pure php static functions like json_encode() or array(). Why doesn't it make sense to see laravel classes behind facades as similar helper functions and not as class dependences?

More than that, many times we're using those "dependences" in a narrow control flow (or conditions) inside the method and the class\method is truly not necessarily dependent on those helpers all the time (for example user class used only if user is authenticated etc.)

  1. In his response to this debate, Taylor Otwel himself said that the use of facades may lead to "responsibility bloat in your classes" meaning we might be tempted to write classes\methods that do too much and not separate them - but I don't understand how using facades instead of injecting all those classes in the contractor or method is different in terms of responsibility - from what I understand it's just a change in where you "declare" those classes - in the method signature or inside it (I understand that has a lot of differences, but don't see one in class responsibility matter). Can someone explain this?

Bottom line I'm asking this because obviously I'm all for facades when they serve as helpers and not as a core part of the class\method purpose, and I want to know I'm not the only one... I'm mostly anxious of having to write every little piece of helpers I'm using as dependences in my classes.

Thanks!



via Chebli Mohamed

Laravel 5.1 create user won't insert added column?

I have added a column for activation token in my users table and I want to add this random string when inserting new users.

So in my AuthController i have this:

protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        'activation_token' => str_random(60),
    ]);
}

The user get's registered but the activation_token column remains empty??? What am I doing wrong?



via Chebli Mohamed

Deployment on Laravel Forge throwing faker not found Exception

I am trying to deploy a laravel project on forge and i am getting the below exception :

Symfony\Component\Debug\Exception\FatalErrorException]  
Class 'Faker\Factory' not found     

I have the faker reference in require-dev in composer.json!

composer.json file

{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"require": {
    "php": ">=5.5.9",
    "laravel/framework": "5.1.*",
    "tymon/jwt-auth": "0.5.*",
    "dingo/api": "1.0.x@dev"
},
"require-dev": {
    "fzaninotto/faker": "~1.5",
    "mockery/mockery": "0.9.*",
    "phpunit/phpunit": "~4.0",
    "phpspec/phpspec": "~2.1",
    "laracasts/testdummy": "1.*",
    "laracasts/generators": "^1.1"
},
"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},
"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"
}

}

Deployment script in Forge:

git pull origin master 
composer install --no-interaction --no-dev --prefer-dist
php artisan migrate --force
php artisan db:seed --class="StaticDataSeeder"

I was able to deploy the same project locally with out any problem and composer update on forge also runs successfully and i can see the faker package getting downloaded.

Please let me know if i am missing something.



via Chebli Mohamed

Assets not being see in laravel 5.1 app

I use scotchbox and have my app set up as such:

app-response-tracker/
  AppResponseTracker/
    app/
    ...
    public/
      css/
        app.css
      js/
        all.js
    resources/
      assets/
      views/
    ...
  public/
    .htaccess/
    favicon.ico
    index.php
    robots.txt

In my layouts.main I have the the following html:

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="App Response Tracker allows you to track the response of applications
    and monitor error output by connecting to a secure end point.">
    <meta name="author" content="Adam Balan">

    <link rel="icon" href="../../favicon.ico">

    <title>App Response Tracker</title>

    <link href="{{asset('css/app.css')}}" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
        <script src="http://ift.tt/1xwklwE"></script>
        <script src="http://ift.tt/1qIredN"></script>
    <![endif]-->
</head>

The line you care about is: <link href="{{asset('css/app.css')}}" rel="stylesheet">

In chrome this resolves too: http://ift.tt/1WpAHDJ

According to the docs:

asset

Generate a URL for an asset.

$url = asset('img/photo.jpg');

My htaccess file looks like:

Options +FollowSymLinks
RewriteEngine On

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

The site loads fine, the styles don't load at all. How can I fix this?



via Chebli Mohamed

Issue with middleware "Maximum function nesting level of '100' reached, aborting!"

I had a controller, lets call it DummyController, that performs CRUD operations in the root of controllers folder. I have moved dummy controller into a different directory, a level higher, so our DummyController is now in folder named 'r'.

Due to that I have updated the edit form, which is used with dummy controller:

{!! Form::model($message, ['method' => 'PATCH', 'action' => ['r\DummyController@update', $message->id]]) !!} 

And now it's broken. I have tried playing around with controller and narrowed the issue down to middleware that I use in Dummy Controller. I have 'auth' middleware and my own 'role' middleware:

if (Auth::user()->role_id != config('Roles.admin')) {
            return redirect('/');
        }

If I remove one middleware everything starts working, I cant have both running, which is strange because before it worked fine.



via Chebli Mohamed

Creating file using Artisan Command in Laravel 5.1

I have created a Artisan Command for my project with this command:

`php artisan make:console Repositories`

The signature for the above custom command is:

protected $signature = 'make:repository {modelName : The name of the model}';

When this command gets executed / fired, 2 files are created:

  1. app/Http/Repositories/Contracts/modelNameRepositoryContract.php
  2. app/Http/Repositories/Eloquent/modelNameRepository.php

Now, I want that the namespace, the className should be written by default. Just like what we get when firing the make:controller ModelController or make:model Model. Those files have written the default things that it needs to have. I want similar to that only.

I want to populate the file with the namespace, the use namespace and the class/contract name by default. And for that here's the handle() method from Repositories.php file:

/**
 * Execute the console command.
 *
 * @return mixed
 */
 public function handle()
 {
     $modelName = $this->argument('modelName');

     if ($modelName === '' || is_null($modelName) || empty($modelName)) {
         $this->error('Model Name Invalid..!');
     }

     if (! file_exists('app/Http/Repositories/Contracts') && ! file_exists('app/Http/Repositories/Eloquent')) {

         mkdir('app/Http/Repositories/Contracts', 0775, true);
         mkdir('app/Http/Repositories/Eloquent', 0775, true);

         $contractFileName = 'app/Http/Repositories/Contracts/' . $modelName . 'RepositoryContract.php';
         $eloquentFileName = 'app/Http/Repositories/Eloquent/' . $modelName . 'Repository.php';

         if(! file_exists($contractFileName) && ! file_exists($eloquentFileName)) {
             $contractFileContent = "<?php\n\nnamespace App\\Http\\Repositories\\Contracts;\n\ninterface " . $modelName . "RepositoryContract\n{\n}";

             file_put_contents($contractFileName, $contractFileContent);

             $eloquentFileContent = "<?php\n\nnamespace App\\Http\\Repositories\\Eloquent;\n\nuse App\\Repositories\\Contracts\\".$modelName."RepositoryContract;\n\nclass " . $modelName . "Repository implements " . $modelName . "RepositoryContract\n{\n}";

             file_put_contents($eloquentFileName, $eloquentFileContent);

             $this->info('Repository Files Created Successfully.');

         } else {
             $this->error('Repository Files Already Exists.');
         }
     }
 }

I know that the above method is not the correct way to create the file using the Artisan command. So, how should I create the file and populate it with the default things. I could not find it anything related to this in the docs.

So can anybody help me out with this ?

Thanks in advance.



via Chebli Mohamed

What can I monitor if the Laravel queue is running?

I can start the queue as such:

php artisan queue:listen

This works fine, but I would like to monitor if the queue is running, especially important as there doesn't seem to a fallback if it's not.

To be clear, if I queue an email through a controller, like so:

$this->mailer->queue($view, $data, function ($message) use ($toEmail, $toName, $subject) {
    $message
        ->to($toEmail, $toName)
        ->subject($subject);
    });

This will successfully run, but if the queue is not 'listening', the job gets pushed on to the job table, forever.

I am looking for something like \Queue::isListening();



via Chebli Mohamed

vendredi 25 septembre 2015

Larval Reading from API with Limits and Displaying onto View with Pagination

Hi I am a little confused on how can I read from an api with page item limited display and then paginate them onto view with the pagination, such that when I click on the pagination link on the view to view next page, the display will be able to show based on the data from the api?

Here is the scenario of what I am doing, I have an api link that is like this: http://localhost:8888/api/v1/categories, which will display a json list of categories limited to 5 per page like following. And the next page will be http://localhost:8888/api/v1/categories?page=2.

    {
  "data": [
    {
      "id": 1,
      "name": "Arts & Entertainment",
      "status": true,
      "created_at": "2015-09-20 16:19:15",
      "updated_at": "2015-09-25 12:58:52"
    },
    {
      "id": 2,
      "name": "Travel",
      "status": true,
      "created_at": "2015-09-20 16:19:23",
      "updated_at": "2015-09-25 12:59:02"
    },
    {
      "id": 3,
      "name": "Child Development",
      "status": true,
      "created_at": "2015-09-20 16:19:28",
      "updated_at": "2015-09-25 12:59:07"
    },
    {
      "id": 4,
      "name": "Computers / Internet",
      "status": true,
      "created_at": "2015-09-20 16:19:44",
      "updated_at": "2015-09-25 12:59:27"
    }
  ],
  "paginator": {
    "total_count": 15,
    "total_pages": 3,
    "current_page": 1,
    "limit": 5
  }
}

I am using Laravel 5.1, and GuzzleHttp to read this data like so:

public function index()
    {
        $client = new Client(['base_uri' => 'http://localhost:8888/api/v1/']);
        $response = $client->get('categories')->getBody();
        $content = json_decode($response->getContents());

        // how to continue with the pagination and display onto the view with the pagination function?
        return view('categories', ['content' => $content->data]);
    }

Views:

<div class="container">
    <ul>
    @foreach($content as $value)
        <li>{{ $value->name }}</li>
    @endforeach
    </ul>
</div>

Thanks in advance for taking time to look through.



via Chebli Mohamed

Laravel 5 filter main data with relationship

User : id,name,age
Shop : id,user_id,name
Address : id, shop_id, address
Shop Type : id, shop_id, type

A [user] has multi [shop], and the [shop] has multi branch, so it has multi [address], and the [shop] also has multi [type] such as alcohol,food,snack,drink and more.

Now i want get the user's shop with all address and shop type.

In model i use User Class public function shop(){ return $this->hasMany('App\Shop'); }

Shop Class public function address(){ return $this->hasMany('App\Address'); }

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

Address Class public function state(){ return $this->hasMany('App\State'); }

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

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

My Control

public function shop($id)
    {
            $shop = User::where("id",$id)->with('shop.address','shop.type')->first();
    if($shop){
            return response()->json(
                [
                    'shop' => $shop->shop,
                ],
                200,
                array(),
                JSON_PRETTY_PRINT
            );
    }else{
            return false;
    }

Code Above can get all the shop's address and shop's type in the database, but how can i do filter only shop's type = 'food' and 'drink' and country code is us with programming? i try code below, but not work for me :

$type = {'food','drink'};  // Example
$user = {'1'};  // Example

public function shopWithFilter($id,$type,$country)
        {
                $shop = User::where("id",$id)->with('shop.address','shop.type')->where(['shop.type.name'=>$type,'shop.address.country.code',$country])->first();
        if($shop){
                return response()->json(
                    [
                        'shop' => $shop->shop,
                    ],
                    200,
                    array(),
                    JSON_PRETTY_PRINT
                );
        }else{
                return false;
        }

Thanks



via Chebli Mohamed

Change SQL query on Auth, Laravel 5.1

When logging in, the query fails, because "email" is not on "usuario", it's in "persona"

Unknown column 'email' in 'where clause' (SQL: select * from `usuario` where `email` = admin@localhost limit 1)

It's not a solution to change the database model, as not all "persona" are "usuario", but all "usuario" are "persona".

Tried to set the relationships:

class Persona extends Model implements AuthenticatableContract,
                                AuthorizableContract,
                                CanResetPasswordContract
{....}
public function usuario()
{
    return $this->hasOne('App\Usuario');
}
//----------------------------------------------------//
class Usuario extends Model implements AuthenticatableContract,
                                AuthorizableContract,
                                CanResetPasswordContract
{
{....}
public function persona()
{
    return $this->hasOne('App\Persona');
}

Both tables have the same key.

But the query doesn't change, I though maybe Laravel could make an "INNER JOIN" somewhere, don't know if Laravel can do that automatically, so I tried to change the query but don't know exactly where is located.

I thought in a solution like this, but it looks too easy, don't know if would be a good way =/


  • Get EMAIL and PASSWD from post
  • Get the ID, EMAIL and PASSWD from the BD with the SQL
  • If [EMAIL and PASSWD match] Auth::loginUsingId(ID); [ELSE] Return with the errors.

As far as I know, the Auth::loginUsingId(ID); acts like a successful Auth::attempt()... but with this solution I'll need to know how to implement later Throttles and the "remember" option separately... all thoughts are welcome :D



via Chebli Mohamed

Call to a member function isATeamManager() on a non-object

Getting this error "Call to a member function isATeamManager() on a non-object".some one kindly give me the solution.


(RedirectIfNotAManager.php)

<?php

namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Closure;


class RedirectIfNotAManager
{


    public function handle($request, Closure $next)
    {
        if(!$request->user()->isATeamManager())
        {

            return redirect('articles');

        }

        return $next($request);
    }
}

I have googled it and didn't get any solution,since i am new to laravel kindly help me to solve this problem .its in laravel 5.1 . I have tried other examples and still getting this error..

(This is the User.php Model code:)

<?php

namespace App;


class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;

     protected $table = 'users';


    protected $fillable = ['name', 'email', 'password'];


    protected $hidden = ['password', 'remember_token'];


    public function articles()

    {


        return $this->hasMany('App\Article');
    }

    public function isATeamManager()
    {

        return false;
    }
}



via Chebli Mohamed

MethodNotAllowedHttpException in RouteCollection.php line 219

When I storing a post I get this error

MethodNotAllowedHttpException in RouteCollection.php line 219:

What can cause this problem ??

Routes.php:

Route::get('home', 'PostsController@index');
Route::get('/', 'PostsController@index');
Route::get('index', 'PostsController@index');

Route::get('posts', 'PostsController@index');
Route::get('post/{slug}/{id}', 'PostsController@show');
Route::get('posts/sukurti-nauja-straipsni', 'PostsController@create');
Route::patch('posts/store-new-post', 'PostsController@store');
Route::get('post/{slug}/{id}/edit', 'PostsController@edit');
Route::patch('posts/{slug}', 'PostsController@update');


Route::get('tags/{tags}', 'TagsController@show');
Route::get('categories/{categories}', 'CategoriesController@show');

// 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'm using Laravel 5.1 and I can't figure this out for a day..



via Chebli Mohamed

composer + rocketeer + laravel 5.1 - cannot install rocketeer in laravel 5.1.17

I tried to install rocketeer on laravel 5.1.17 using composer but couldn't succeed. enter image description here

Is it incompatible with latest version of laravel or what might be the problem?



via Chebli Mohamed

How can I Install oh-my-zsh

Can I ask some help how can install this in windows10 oh-my-zsh

are there any prerequisite on this ?

Thank you in advance.



via Chebli Mohamed

In Laravel 5.1 import export excel integratation not working

In searching i found link http://ift.tt/1Fy5Lg6 but it support to Laravel 5. I need to integrate in Laravel 5.1

Please suggest



via Chebli Mohamed

How to unit test my Service implementation Laravel 5?

I want to unit test my ServiceImpl but i dont know how ?

This is my Service :

interface CommentService { public function findAll($class, $classId, ApiRequest $request = null); }

This is my Service Implemantation:

class CommentServiceImpl implements CommentService
{    
public function findAll($class, $classId, ApiRequest $request = null)
    {
        $model = NamespaceConstants::NAMESPACE_CONST . $class;

        $comment = Comment::where('commentable_type', $model)->where('commentable_id', $classId)->get();

        if ($request != null) {
            $comment->load($request->getRelations());
        }

        return $comment;
    }
}



via Chebli Mohamed

What does ::class mean in laravel 5.1 [duplicate]

This question already has an answer here:

When I add custom service providers in app.php, I used to insert as follows

'Something\Somewhere\SomeProvider',

But in Laravel 5.1, It changes as follows

'Something\Somewhere\SomeProvider::class',

What does it mean ?? I like to know about ::class usage in php.



via Chebli Mohamed

jeudi 24 septembre 2015

Laravel 5 model validation and authorization

I am facing a dilemma on how to implement validation in my laravel project, let me explain the situation.

  1. I am using an angular JS front end user interface and communicating to laravel using restful resource controllers.
  2. I am using form request validation in my controller's store() and update() methods to validate the data via the rules() method and determining the authorization using authorize() method, which ensures both that my data is correct, and only users with correct permission levels can add/edit data. Everything is working well at this point, so long as the data is coming via a form/ajax request made to the api.

Now, here is the problem. Sometimes the insert/edit operation needs to be done programatically, for e.g. whenever a row is created in table A, a row needs to be created in table B, but before doing so, it should also run the same validation rules and check authorization that it would do if table B was created using a form request, but if I just called say TableA::Create([]) the row would be created without any validation.

Sure, I can use Validator::make() inside the model as well but then, a) it makes the model cluttered b) is a repetition of code

So, my objective is to ensure that no matter how Table A's records are going into the database, if its done from the application, the checks will be performed before saving the data, while keeping the validation and authorization rules central. It seems to me that the way to go is to put a hook onto the model's "saving" event and somehow trigger the formrequest validator? But I am not sure.

I saw Jeffrey Way's automatic model validator, but that is for Laravel 4. Is there any elegant way to do this in Laravel 5.x ?

Also, as an add-on question, when I had asked this question elsewhere, a few people said they were "not a fan of model based validation", without explaining why it is not a good idea for them, so I would also like to know what are the drawbacks of model based validation?



via Chebli Mohamed

Laravel 5.1 Multyple Auth With two database

Continue from this question

Lets say I have :

Database_one:
users[
username,
password
]

And

Database_two:
employee[
username,
password
]

I was done make custom auth with database_one and work perfectly. in the same application, I want to create same auth but with database_two

I was found default auth laravel is

App\User
App\Http\Controllers\Auth
Config\Auth

What I must do now ? copy-paste default laravel auth file and change/modif value ? Or how ?

I am new to laravel,

Thanks for Adv.

Angga.



via Chebli Mohamed

Laravel Authentication using Ajax

I had a problem with authentication using ajax calls in Laravel 5.1. It is related to csrf token. Any idea?



via Chebli Mohamed

foreach() limited to 20 iterations in blade?

I have a foreach in blade that goes through an array with 25-30 or more elements and it always stops after 20.

I don't get any error, the script continues normally after that and I can't find any reason for it.

This is how it works: I upload a number of files (25-30 or more) and it doesn't take long (under a minute to return the view). I get the files information, perform a database query and send the array to the view.

return view('checkfiles')->with('files', $files);

In the view I have:

@foreach ($files as $file)
    <div class="block">
        <input type="text" name="data[{{ $file->count }}][packagename]" value="{{ $file->packagename }}">
     ...
    </div>
@endforeach

And no matter how many files or what files I upload, I only get this displayed 20 times.

Any idea?



via Chebli Mohamed

Laravel resetPassword() throws with "Attempt to assign property of non-object"

I want to change the password for the current user:

public function postChange(Request $request)
{
    $user = \Auth::user();

    $this->validate($request, [
        'oldpassword' => 'required',
        'password' => 'required|confirmed|min:6',
    ]);

    if (\Hash::check($request->oldpassword, $user->password)) {
        $this->resetPassword($user->email, $request->password);
    } else {
        return \Redirect::back()->withErrors('The old password is incorrect.');
    }
}

but I get this error:

ErrorException in ResetsPasswords.php line 134:

Attempt to assign property of non-object

What do I have to change to make this work?

$this->resetPassword($user->email, $request->password);



via Chebli Mohamed

Customize Authentication in Laravel

I'm using Laravel 5.1, and I need to use existing user table that has its own password algorithm. After hours and hours of research, I've found solution and here are the steps. Hope this helps Laravelers.



via Chebli Mohamed

How to call blade senteces when using javascript

I'm having a rough time trying to figure out how to make my blade sentences to be ignore as a string when I use an ajax method.

this is my code so far

Ajax method

/* SEARCH BREAKFAST AJAX */
    $('#search').on('change',function(e) {
        var category_id = e.target.value;
        console.log("category_id : "+category_id);
        $.get('dishes/ajax_breakfast?search='+category_id,function(data){
            console.log(data);

            $.each(data,function(index,breakFastObj){
                $("#dishes").append("<li class='list-group-item'><span class='badge'>{{ link_to('dishes/' ."+ breakFastObj.id+" ,'Ver',null) }}</span>"+
                "Nombre del platillo : "+breakFastObj.name+"  - Categoria : {{ \\App\\Category::find(+"+breakFastObj.category_id+")->description_es+ }} </li>");

            });
        },'json');
    });

I want to flecht data from my model Category and also want to use the link_to(), but I understand that Javascript makes those:

{{ link_to('dishes/' ."+ breakFastObj.id+" ,'Ver',null) }}
{{ \\App\\Category::find(+"+breakFastObj.category_id+")->description_es+ }}

strings and the output I get is:

Nombre del platillo : Crepa - Categoria : {{  \App\Category::find(1)->description_es }} {{ link_to('dishes/.'3,'Ver',null)}}

and What I expect to get is:

Nombre del platillo : Crepa - Categoria : Desayunos - Ver

I would appreciate some help with this one or even I know if it is possible.



via Chebli Mohamed

Class does not exist for laravel routes

Laravel 5.1

This seems strange to me:

Route::group([
    'middleware'=>['auth','acl:view activity dashboard'],
    'prefix' => 'api/v1'
], function(){
    Route::controller('investment-transactions', 'Api\V1\Investments\InvestmentTransactionsController');
    Route::controller('investment-transactions/{offeringID}', 'Api\V1\Investments\InvestmentTransactionsController@getTransactionsForOffering');
});

Seems pretty normal to me, the controller:

namespace App\Http\Controllers\Api\V1\Investments;

use App\Brewster\Models\Company;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

class InvestmentTransactionsController extends Controller {

    public function __construct() {

    }

    public function getIndex() {
        echo 'Here';
    }

    public function getTransactionsForOffering($offeringID) {
        echo $offeringID;
    }
}

Ok so the action and the controller do exit, but when I run: php artisan routes:list I get:

 [ReflectionException]                                                                                                     
  Class App\Http\Controllers\Api\V1\Investments\InvestmentTransactionsController@getTransactionsForOffering does not exist 

Well obviously App\Http\Controllers\Api\V1\Investments\InvestmentTransactionsController@getTransactionsForOffering is not a class, how ever: App\Http\Controllers\Api\V1\Investments\InvestmentTransactionsController is and getTransactionsForOffering is an action.

Whats going on?



via Chebli Mohamed

Laravel 5 get user with relationship‘s and multi relationship

Database Below

User : id,name,age
Shop : id,user_id,name
Address : id, shop_id, address
Shop Type : id, shop_id, type

A [user] has multi [shop], and the [shop] has multi branch, so it has multi [address], and the [shop] also has multi [type] such as alcohol,food,snack,drink and more.

Now i want get the user's shop with all address and shop type.

In model i use User Class

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

Shop Class

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

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

My Control

public function user($id)
    {
            $user = User::where("id",$id)->with('shop.address')->first();
    if($user){
            return response()->json(
                [
                    'user' => $user,
                ],
                200,
                array(),
                JSON_PRETTY_PRINT
            );
    }else{
            return false;
    }

Code above can get all user's shops and shops's address but how can i get also shops's type?

Thanks



via Chebli Mohamed

Laravel 5.1 global scopes... Where should I go?

Well, I've started with Laravel just a few weeks ago, so sorry if I'm repeating something obvious but... here's the thing:

I've got a couple of query scopes in a Photo model:

public function scopeSkipFirst($query) 
{
    return $query->where('id', '>', 1);
}

public function scopeSearch($query, $search) 
{
    return $query->where('title', 'LIKE', "%$search%");
}

Now, I want the first one to be executed everytime I make an Eloquent query by that model, like in Photo::all(); and I want the second query scope to be available to any other model.

What's the best practice way to do this? Are both scenarios "global scopes"? I've been reading a few posts (like this one), but I have no clear ideas about which documentation should I refer (Laravel's 4.2 # Global scopes section; 5.1 Eloquent's # Events; ¿?).



via Chebli Mohamed

How to set custom attribute labels for nested inputs in Laravel

I'm trying to get custom labels in the error messages. My inputs are nested and i am able to validate them using dot notation (e.g. POLICY.HOLDER.NAME ). They have to be nested and all caps to match the db structure so I can easily mass assign them.

Using the same notation in 'attributes' => ['POLICY.HOLDER.NAME' => 'Policy Holder'] in resources/lang/en/validation.php yielded no result.

I'm just trying to get them to match the labels i've set in the form.



via Chebli Mohamed

How to Get Laravel Relationship Where Related Model Created After Date

I have a DateTime Object, and I have many posts belonging to a User. My Relationship on the User model is set up like:

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

I can retrieve the logged in user's posts by doing:

Auth::user()->posts

However, I can't seem to retrieve posts that were made after a certain date. I tried:

/** \DateTime $date **/
$posts = \Auth::user()->posts->where('created_at','>', $date);

But it just returns an empty array and I'm certain that there are posts which exist that were created after that date. What is the correct way to perform this query?



via Chebli Mohamed

Laravel 5.1 Eloquent relation Eager loading not working

I tried all the answers already on the forum, none helped me.

App\User.php Model defines hasOne relationship

public function apikey()
{
    return $this->hasOne('App\ApiKey', 'user_id', 'user_id');
}

App\ApiKey.php Model defines reverse relationship

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

Now I have a transform function with is call from controller return $this->response->withItem(**$users**, new UserTransformer);

App\Transformer\UserTransformer.php

public function transform($resource) //$resource is a users object
{
    $user_id = (int) $resource->user_id;
    $apiKey = $resource->apikey->key;
    return [
        'user_id' => $user_id,
        'apikey' => $apiKey
    ];
}

I get following error at $apiKey = $resource->apikey->key;

Trying to get property of non-object

I do not understand where am I going wrong Please suggest.

Thanks,

K



via Chebli Mohamed

Laravel Spark doesn't pull in css correctly

I am playing around with Spark in order to learn how to use it. I did a new install under Homestead following the install instructions. The css link generated fro the page at the route / is

 <link href="http://ift.tt/1L7VV7k" rel="stylesheet">

No css was generated. So, the home page is jacked.Can anyone help me track down the problem?



via Chebli Mohamed

Laravel homestead: Unknown database 'projectadmin_db'

I am new to laravel. I use homestead for development. I have two database connection

database.php

'cust_main_db'   =>  [
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'project_db',
        'username'  => 'homestead',
        'password'  => 'secret',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],
    'admin_main_db'   =>  [
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'projectadmin_db',
        'username'  => 'homestead',
        'password'  => 'secret',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

Homestead.yaml

databases:
    - homestead

In my local mysql has both databases project_db and projectadmin_db

When I run the project http://ift.tt/1mROfU6 it shows SQLSTATE[HY000] [1049] Unknown database 'projectadmin_db'

What I have missed here? Correct me if anything wrong.



via Chebli Mohamed

Parse error after deploy Laravel 5.1 on shared hosting

I am using Laravel 5.1

To get rid of Public folder:

  1. I moved everything in a folder named 'root' except public folder.

  2. Move all public folder content in Root.

  3. Changed require __DIR__.'/root/bootstrap/autoload.php'; & $app = require_once __DIR__.'/root/bootstrap/app.php'; in index.php at root folder.

Everything is working perfectly in localhost. I uploaded my project in a shared hosting. And change database information in .env and change the url in Config\App.php 'url' => 'localhost', to 'url' => 'http://ift.tt/1jdbkqA',.

Now when I go to myproject.com it shows a Parse error Parse error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in /home/zamzamtransport/public_html/index.php on line 50

index.php:

require __DIR__.'/root/bootstrap/autoload.php';

$app = require_once __DIR__.'/root/bootstrap/app.php';

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

$response->send();

$kernel->terminate($request, $response);

Another problem is my .env file is accessible.



via Chebli Mohamed

mercredi 23 septembre 2015

Retrieve all rows from table except few rows in laravel

I am using Laravel 5.1 & MySQL as backend to serve REST-API requests made from the mobile app.

I have a Cart table and Items table. So whenever user comes to 'Items screen' in his mobile App, In the backend I should perform 2 tasks.

  1. First check if any Items are there in his cart. If yes (i.e.,there are items in Cart table), then fetch those items from Cart table and the remaining items from Item table.
  2. If there are no items in Cart, then I will easily fetch all items from the Items table and show it to user.

I am struck by not able to perform the task 1. Because I am first retrieving all the item_ids from the Cart table. It will return a collection. Now I should check if these item_ids(from cart table) are present in Items table. If yes, don't fetch those items from Items table, BUT fetch all other items from Items table. Combine those items from Items table & items from Cart table and show it to user. How can I achieve this?

Currently, problem is, I am getting all 'item_ids' from Cart table. It returns a collection of item-ids. Using foreach() loop, for every item_id, I am quering Items table as follows: ("where('item_id','!=',$getItemId)->get();")

$itemDetails = ItemBng::where('store_id','=',$store_id)->where('category_id','=',$category_id)->where('subcategory_id','=',$subcategory_id)->where('item_id','!=',$getItemId)->get();

And it returns collection checking against each individual item. and replaces collection with every new iteration in foreach loop.

Here is the function in my CartController:

public function getItemsWithCartItems($uuid,$store_id,$category_id,$subcategory_id,$subsubcategory_id=null)
{
    try
    {
        $getCartItems = UserCartDetailBng::where('uuid','=',$uuid)->get();
        if($getCartItems->isEmpty()) //Performing task 2. No problem here.
        {
            if($subsubcategory_id==null || $subsubcategory_id==0) // Bcoz, subsubcategory_id is optional
            {
                $itemDetails = ItemBng::where('store_id','=',$store_id)->where('category_id','=',$category_id)->where('subcategory_id','=',$subcategory_id)->get();
                if($itemDetails->isEmpty()){
                    return ResponseService::buildFailureResponse("Store Item not found");
                }
            }
            else
            {
                $itemDetails = ItemBng::where('store_id','=',$store_id)->where('category_id','=',$category_id)->where('subcategory_id','=',$subcategory_id)->where('subsubcategory_id','=',$subsubcategory_id)->get();
                if($itemDetails->isEmpty()){
                    return ResponseService::buildFailureResponse("Store Item not found");
                }
            }
            $count = $itemDetails->count();
            $data = array('count'=>$count,'result'=>$itemDetails);
            return ResponseService::buildSuccessResponse($data);
        }
        else  //Performing task 1. Here is the problem.
        {
          // I am using "where('item_id','!=',$getItemId)->get()" And it returns collection checking against each individual item. and replaces collection with every new iteration in foreach loop.
            foreach($getCartItems as $getCartItem)
            {
                $getItemId = $getCartItem->id;
                if($subsubcategory_id==null || $subsubcategory_id==0)
                {
                    $itemDetails = ItemBng::where('store_id','=',$store_id)->where('category_id','=',$category_id)->where('subcategory_id','=',$subcategory_id)->where('item_id','!=',$getItemId)->get();
                    if($itemDetails->isEmpty()){
                        return ResponseService::buildFailureResponse("Store items not found");
                    }
                }
                else
                {
                    $itemDetails = ItemBng::where('store_id','=',$store_id)->where('category_id','=',$category_id)->where('subcategory_id','=',$subcategory_id)->where('subsubcategory_id','=',$subsubcategory_id)->where('item_id','!=',$getItemId)->get();
                    if($itemDetails->isEmpty()){
                        return ResponseService::buildFailureResponse("Store items not found");
                    }
                }
                $count = $itemDetails->count();
                $data = array('count'=>$count,'result'=>$itemDetails);
                return ResponseService::buildSuccessResponse($data);
            }
        }
    }

please help me solve this problem, TIA.



via Chebli Mohamed

Laravel Change Login URL - MethodNotAllowedHttpException

i want change laravel login url from /auth/login to login

already make change in AuthController

protected $loginPath = 'login';

and routes

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

i can access login page if manually go to that page

but if redirect to login page after trying to access page already protected with Middleware its still redirect to /auth/login



via Chebli Mohamed

Calculating time difference with values retrieved from MySQL TIME field

I've done a bit of searching and there is a bunch of information on calculating time difference between two times using strtotime('09:00:00) and then putting this against another value.

Currently, I have a database that stores regular hours for staff like so:

+----------+-----------+------------+-------------+--------------+
| staff_id |    day    | start_time | finish_time | total_breaks |
+----------+-----------+------------+-------------+--------------+
|        1 | Monday    | 18:00:00   | 22:00:00    |            0 |
|        2 | Wednesday | 09:00:00   | 17:30:00    |           30 |
+----------+-----------+------------+-------------+--------------+

start_time and finish_time are stored as TIME values in MySQL and total_breaks as an INT which I should probably convert to TIME values as well and represent as 00:30:00 or 00:00:00 for consistency.

What I want to be able to do is display a table that displays all of this information, as well as their total hours worked and then total hours minus any breaks.

I've been able to generate a table with the staff_id, day, start_time and finish_time but am struggling to figure out the best way to calculate the total amount of time worked etc.

I'm using Laravel, and have read that strtotime('00:00:00') is a great way to do this but this won't work as I'm not using a string but rather pulling the time from the database.

What is the best way to calculate the time difference between the two times, and then take in to account the breaks as well.

Have I even set this up correctly? I don't want to set the times up as a DATETIME as I'm just wanting to calculate the time difference of their normal working hours which they do from week to week - although I can always use dummy dates to get this working if necessary.

Any ideas?



via Chebli Mohamed

Load Datatables with Json Object as source come from API on Laravel 5.1

i am making a datatables which have datsource come from my API, this API will return the JSON and return to view (jquery) in order to load on datatables. But i don't know why the datatables ajax is automatically add params like bellow to the url, so the website report to me the 404 error. How can i fix this?, this is my code to call ajax to the controller route.

 <script>

      $("#example1").DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": "/getAllStaff/1",
        "columns": [
            { "data": "UserCode" },
            { "data": "FullNameSta" },
            { "data": "EmailSta" },
            { "data": "PhoneNumberSta" },
            { "data": "UserRoll" },
            { "data": "Status" },
            { "data": "Status" }
        ]
    });
</script>

And this is my route (call to controller to return data to ajax call):

Route::get('/getAllStaff/{page}',['as' => 'Value', 'uses' =>  'admin\adminFunctionController@getDisplayInfor']);

Here is my controller code:

 public function getDisplayInfor($page)
{

    $params = ''.$page;
    $action = 'getAllStaff';

    $result = ApiController::getAPI($params, $action);
    try{
        if($result->{'success'}){
            return response()->json(['recordsTotal'=>$result->{'CountData'}, 'recordsFiltered'=>$result->{'CountData'}, 'data'=>$result->{'data'}]);
        }else{
            return response()->json(['success'=>false, 'error'=>$result->{'error'}]);
        }
    }catch (\Exception $ex){
        return response()->json(['success'=>false, 'error'=>$ex]);
    }
}

So i was tried to get it on postman and it's working fine, but it isn't when i call by ajax cause the datatables auto add params to the url and more than that, when i tried to call many time to the ajax i see that i have some request that return data to me. That's weird, if the route is the root of the problem i don't think it can return data in some request!.

Thanks.



via Chebli Mohamed

Upload file option not shown in trumbowyg wysiwyg editor

I am using trumbowyg wysiwyg editor in my laravel app. In the editor, upload option is not show though upload plugin is already installed. enter image description here



via Chebli Mohamed