mercredi 1 juin 2016

ModelNotFoundException when passing Model Object in Event constructor

This is my controller:

$transaction = new ProductTransactionLog();
Event::fire(new SendResponseToProduct($response, $transaction));

This is event class (SendResponseToProduct):

use Illuminate\Queue\SerializesModels;
use App\Models\ProductTransactionLog;

class SendResponseToProduct extends Event
{
    use SerializesModels;

    public $response = [];
    public $transaction;

    /**
     * Create a new event instance.
     */
    public function __construct($response = [], ProductTransactionLog $product_transaction)
    {
        // dd($transaction);
        $this->response = $response;
        $this->transaction = $product_transaction;
        // dd($this->transaction);
    }
}

This is in the EventServiceProvider:

protected $listen = [
        'App\Events\SendResponseToProduct' => [
            'App\Listeners\ResponseToProductListener',
        ],
    ];

When I run the controller, i.e when I fire the Event, I get this weird error:

NotFoundHttpException in Handler.php line 46: No query results for model [App\Models\ProductTransactionLog].

When I dd in the Event constructor, I get the object. When I uncomment dd, I get the error again.

When I dd in the Listener class, I get this same error. It does not reach the Listener class.

What is it that I am missing here?



via Chebli Mohamed

Divide collection into parts on laravel

I have this curriculum type of data that should be displayed and unequally divided. See this image

What I want is to achieve something like thisthis

Here's my code:

StudentController.php

public function show($id)
{
    $student = Student::with('course', 'course.curriculum', 'course.curriculum.subjects')->findOrFail($id);

    return view('students.show', compact('student'));
}

show.blade.php

<div class="panel-body">
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Course Code</th>
                <th>Descriptive Title</th>
                <th>Units</th>
                <th>Prerequisites</th>
                <th>Grade</th>
            </tr>
        </thead>

        <tbody>
            @foreach($student->course->curriculum->subjects as $subject)
            <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td>98</td>
            </tr>
            @endforeach
        </tbody>
    </table>
</div>



via Chebli Mohamed

How to manage sms and reply from webapp through twilio

I'm creating a messaging web application with laravel 5.1 and twilio and i'm using laravel-twilio package.

Settings and configuration already done in twilio dashboard

  1. In Programmable SMS section i'hv created a messaging service with copilot which includes a single phone number ((xxx) xxx-xxx).

  2. Given a Inbound request url.

My laravel application code

I have simple user to user messaging where both user are online where nothing to do with twilio. But suppose one of the user is offline and another one is online and the online user send a chat message to offline user then i have to notify the the offline user through an sms to this user's phone number via twilo.

    public static function notifyOfflineUser($user,$reply_text){
            $message = "Mysite: ".$user->user_from->firstname.", '".strip_tags($reply_text)."' Reply via mysite ".url('general-message')." or SMS";
            if($user->profile->mobile) {
                try {
                    \Twilio::message($user->profile->mobile, $message);
                } catch (\Exception $e) {

                }
            }
        }

It's sending a sms to the user from the twilio phone number.

Where the user can reply to this message form his/her phone to this number. And if the reply succeded i have to add the message to the online user's message board.

//Inbound request url routed to this url with From number, body and other data.

    public function smsReply(Request $request){

        $user_id_to = Profile::where('mobile', $request->get('From'))->first(['user_id'])->user_id;
        $body = $request->get('Body');

        $user_id_from = Message::where('user_id_to', $user_id_to)->orderBy('id', 'desc')->first()->user_id_from;

        //dd($request->all());
        $message = new Message();
        $message->user_id_from                  = $user_id_to;
        $message->user_id_to                    = $user_id_from;
        $message->message                       = $body;
        $message->save();
        return response()->json(true);
    }

Now if multiple online user send chat message to this offline user, offline user will get miltiple sms from the same twilio number and those all sms are coming in a same stack, that mean it's not coming in different sms if he/she reply to the sms it will send to the same number, and all online user will get same message added in their message board.

Now here is my question..

Is there anything else need form twilio like multiple number, short codes, tollfree or i have to do the trick with my laravel code so i can send each sms to the offline user's phone as a different sms so i can distinguish them from inbound request url ? Feel free to ask me if more information needed.



via Chebli Mohamed

ReflectionException - Middleware class does not exist Laravel 5.2

I am building an API with stateless HTTP basic authentication in Laravel 5.2, as per documentation Stateless HTTP Basic Authentication , I have created following Middleware

app/Http/Middleware/AuthenticateOnceWithBasicAuth.php

<?php

namespace Illuminate\Auth\Middleware;

use Auth;
use Closure;

class AuthenticateOnceWithBasicAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */

    public function handle($request, Closure $next)
    {
        return Auth::onceBasic() ?: $next($request);

    }

}

And then registered it in Kernel.php

app/Http/kernel.php

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'auth.basic.once' => \App\Http\Middleware\AuthenticateOnceWithBasicAuth::class,
];

I am using it in route as follows

Route::group(['prefix' => 'admin', 'middleware' => 'auth.basic.once'], function () {

Route::get('service/create', function ()    {
    return response()->json(['name' => 'Abigail', 'state' => 'CA'], 200);
});

});

But it is giving me

ReflectionException in Container.php line 734: Class App\Http\Middleware\AuthenticateOnceWithBasicAuth does not exist

enter image description here

I have run following commands but with no success

composer dump-autoload
php artisan clear-compiled
php artisan optimize 

Any help would be much appreciated. Thanks in advance.



via Chebli Mohamed

BadMethodCallException in Controller.php line 283:

The below one is my controller code from AdminController.php

namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    use Schema;
    use Illuminate\Database\Schema\Blueprint;
    use App\Http\Requests;
    use App\Http\Controllers\Controller;
    use Illuminate\Support\Facades\Input;
    use Session;
    use Redirect;
    use Response;
    use App\KGB;

    class AdminController extends Controller
    {
        public function add_kgb()
        {
            $kgb_type = Input::get('kgb_type');
            $kgb_price = Input::get('kgb_price');
            $region_id = Input::get('region_id');
            $brand_id = Input::get('brand_id');
            $count = KGB::count();
            $kgb_id = "KGB".sprintf("%05d", ($count+1));

            $add_kgb = new KGB;
            $add_kgb->kgb_id = $kgb_id;
            $add_kgb->kgb_type = $kgb_type;
            $add_kgb->kgb_price = $kgb_price;
            $add_kgb->region_id = $region_id;
            $add_kgb->brand_id = $brand_id;
            $add_kgb->flag = '1';
            $add_kgb->save();
            Session::flash('kgb_success','Successfully Added KG Billing!');
            return Redirect::to('kgb');
        }

        public function edit_kgb()
        {
            $kgb_type = Input::get('kgb_type');
            $kgb_price = Input::get('kgb_price');
            $region_id = Input::get('region_id');
            $brand_id = Input::get('brand_id');
            $kgb_id = Input::get('kgb_id');

            KGB::where('kgb_id', $kgb_id)->update(array('kgb_type' => $kgb_type, 'kgb_price' => $kgb_price, 'region_id' => $region_id, 'brand_id' => $brand_id));

            Session::flash('kgb_success_edit','Successfully Edited KG Billing!');
            return Redirect::to('kgb');
        }

        public function kgb_status($id)
        {
            $status = KGB::where('id',$id)->pluck('status');
            if($status=='0')
                KGB::where('id',$id)->update(array('status' => '1'));
            else
                KGB::where('id',$id)->update(array('status' => '0'));

            Session::flash('kgb_success_status','Successfully Edited KG Billing!');
            return Redirect::to('kgb');
        }
    }

This is my base controller code

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;

abstract class Controller extends BaseController
{
    use DispatchesJobs, ValidatesRequests;
}

And this is my route code

Route::get('kgb', function () {
    return view('admin.kgb');
});

Route::post('add_kgb', 'AdminController@add_kgb');
Route::post('edit_kgb', 'AdminController@edit_kgb');
Route::get('kgb_status/{id}', 'AdminController@kgb_status');

this one is my model

namespace App;

use Illuminate\Database\Eloquent\Model;

class KGB extends Model
{
    protected $table = 'kg_billing';
}

Till now all my controllers and routes are working but now this method is throwing an error. Please help me out

This is my error



via Chebli Mohamed

update multiple array values with multiple ids in laravel 5.1

My query as follows

        $dueid = array('1','2');

        for($n = 0; $n< count($post['percentage']); $n++) {

            $due=invoiceduedates::whereIn('id',$dueid)
            ->update(array(
            'percentage' => $post['percentage'][$n],
            'amount'=>$post['pamount'][$n],
            'date' => $post['date'][$n]

            )
            );

        }

But in table,at 1st and 2nd ids the 2nd array data is getting updated.Please help me to sort it out.



via Chebli Mohamed

Laravel5.1: user-wise view restriction

I want to have view restriction for different user in my Laravel5.1 application. The application is an online POS. The users of the software are Admin and employees. First of all I have a login panel. User must log into the system before using it. Then, I want to restrict employee to view Sale Report page and to Add new Item. Only Admin can perform those operations. How can I implement this view restriction using Laravel5.1.



via Chebli Mohamed