samedi 31 octobre 2015

How do I get the name of a Job in larval 5

I've tried $this->getName() inside the laravel Job

This is my sample job class

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

    private $path;
    private $filename;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($path, $filename)
    {
        $this->path = $path;
        $this->filename = $filename;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
             echo  “Name  = “. $this->getName();    
    }
}

But the method above tells me getName() isn't defined.

Thanks for your help.



via Chebli Mohamed

Adding an update method laravel

I have a register function done as shown below and was wondering how can I add an update method. Do I just add another route for my update and a controller function for it? Am I on the right track? Is the below correct? When run, it tells me fatal exception, unexpected return ..

route.php

Route::post('manage_accounts', 'ManageAccountsController@register');
Route::post('manage_accounts', 'ManageAccountsController@update');

controller.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\StoreNewUserRequest;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Hash;

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

class ManageAccountsController extends Controller
{
    public $userRepository;

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

    public function index() 
    {
        $users = User::orderBy('name')->get();
        $roles = Role::all();

        return view('manage_accounts', compact('users', 'roles'));
    }

    public function register(StoreNewUserRequest $request)
    {
        // process the form here
        $this->userRepository->upsert($request);
        Session::flash('flash_message', 'User successfully added!');

        return redirect()->back();
    }

    public function update(UpdateUserRequest $request)
    {
        $this->userRepository->upsert($request)
        //Session::flash('flash_message', 'User successfully updated!');

        return redirect()->back();
    }
}

class UserRepository {

    public function upsert($data)
    {

            // Now we can separate this upsert function here
        $user = new User;
        $user->name     = $data['name'];
        $user->email    = $data['email'];
        $user->password = Hash::make($data['password']);
        $user->mobile   = $data['mobile'];
        $user->role_id  = $data['role_id'];

            // save our user
        $user->save();

        return $user;
    }
}



via Chebli Mohamed

Keeping modal dialog open after validation error laravel

So basically I have a blade.php, controller page and a form request page(validation). I'm trying to keep my modal dialog open if there is an error but I just cant figure it out, what part of code am I missing out on or needs to be changed?

blade.php

<div id="register" class="modal fade" role="dialog">
...

<script type="text/javascript">
if ({{ Input::old('autoOpenModal', 'false') }}) {
    //JavaScript code that open up your modal.
    $('#register').modal('show');
}
</script>

Controller.php

class ManageAccountsController extends Controller
{
    public $userRepository;

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

    public function index() 
    {
        $users = User::orderBy('name')->get();
        $roles = Role::all();

        return view('manage_accounts', compact('users', 'roles'));
    }

    public function register(StoreNewUserRequest $request)
    {
        // process the form here
        $this->userRepository->upsert($request);
        Session::flash('flash_message', 'User successfully added!');

        //$input = Input::except('password', 'password_confirm');
        //$input['autoOpenModal'] = 'true'; //Add the auto open indicator flag as an input.

        return redirect()->back();
    }
}

class UserRepository {

    public function upsert($data)
    {

            // Now we can separate this upsert function here
        $user = new User;
        $user->name     = $data['name'];
        $user->email    = $data['email'];
        $user->password = Hash::make($data['password']);
        $user->mobile   = $data['mobile'];
        $user->role_id  = $data['role_id'];

            // save our user
        $user->save();

        return $user;
    }
}

request.php

class StoreNewUserRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        // create the validation rules ------------------------

        return [
        'name'             => 'required',                        // just a normal required validation
        'email'            => 'required|email|unique:users',     // required and must be unique in the user table
        'password'         => 'required|min:8|alpha_num',
        'password_confirm' => 'required|same:password',           // required and has to match the password field
        'mobile'           => 'required', 
        'role_id'          => 'required'
        ];
    }
}



via Chebli Mohamed

Processing multiple files in Laravel 5.1 (as an API)

So this seems like a pretty basic thing but I can't find a lot of documentation online about what's going on....

I'm trying to run through a list of files using Laravel 5.1 and I can only return/process/see the first file. I'm using Postman to send the request to the API (so I know multiple is enabled in the POST request) and then iterating through that a few different ways:

public function files(Request $request)
{
    foreach($request->files as $file)
    {
        var_dump($file);
    }
}

even:

public function files()
{
    foreach($_FILES['files'] as $file)
    {
        var_dump($file);
    }
}

I'm always returning:

string 'Screen%20Shot%202015-10-23%20at%2010.07.23%20AM.png' (length=51)
string 'image/png' (length=9)
string '/tmp/phpZw1ALu' (length=14)
int 0
int 13687

Why is this happening? What can I do to see multiple files in Laravel 5.1's controllers?



via Chebli Mohamed

How to inject dependencies to a laravel job

I'm adding a laravel job to my queue from my controller as such

$this->dispatchFromArray(
    'ExportCustomersSearchJob',
    [
        'userId' => $id,
        'clientId' => $clientId
    ]
);

I would like to inject the userRepository as a dependency when implementing the ExportCustomersSearchJob class. Please how can I do that?

I have this but it doesn't work

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

    private $userId;

    private $clientId;

    private $userRepository;


    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($userId, $clientId, $userRepository)
    {
        $this->userId = $userId;
        $this->clientId = $clientId;
        $this->userRepository = $userRepository;
    }
}



via Chebli Mohamed

Eloquent relation with custom foreign - other key value

Is there a way to create an Eloquent relation function based on custom foreign - other key value?

For example I have level relation:

public function level(){
    return $this->belongsTo(Level::class, 'level_number', 'number');
}

And I want to do something like this:

public function nextLevel(){
    return $this->belongsTo(Level::class)->where('number', '=', $this->level_number + 1);
}

Is this possible or I have to write a raw query?



via Chebli Mohamed

Mass Assignment Expection with create and update methods

I have strange issue while using create or update methods on laravel tinker although i added $fillable array i receive mass assignment exception on 'title' or whatever field i added to the create or update methods

table fields as follows

  1. id
  2. title
  3. body
  4. published_at
  5. timestamps

model as follows

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $fillable = ['title','body'];
}

command line i typed

$article = App\Article::create(['title' => 'ready']);



via Chebli Mohamed

error in getting results from Excel file in Laravel 5.1

I am trying to retrieve results from an excel file to save the results in the database column. Here is what I am trying

public function addRecords(Request $request){
        $file = $request->get('file');
        //echo $file;
        Excel::load($file, function($reader){
            $results = $reader->get()->toArray();

            echo $results;
            foreach($results as $key => $value){
                $sim = new Sim();
                $sim->msisdn = $value['msisdn'];
                $sim->imei = $value['imei'];
                $sim->issued_to = $value['issued_to'];
                $sim->associated_with_employee = $value['associated_with_employee'];

                $sim->save();
            }
        });
    }

I am getting error Undefined index: msisdn|imei|issued_to|associated_with_employee. What I am doing wrong here?



via Chebli Mohamed

Phpunit Laravel Test Error

I have the following test:

class AuthTest extends TestCase
{
    use DatabaseTransactions;


    /** @test */
    public function a_user_may_login()
    {

        $this->login()->see('Welcome back!');
    }

    protected function login($user = null)
    {
        $user = $user ?: $this->factory->create('App\User', ['password' => 'password']);

        return $this->visit('login')
            ->type($user->email, 'email')
            ->type('password', 'password')
            ->press('Log in');
    }
}

But its throwing the following error: ErrorException: Undefined property: AuthTest::$factory

Any ideas why it's throwing this error?



via Chebli Mohamed

Moving my CSS code out of my html file and into it's own file breaks everything

I'm building a laravel app and initiatlly, wanted to get it up and running quickly so had all of my css and html file all in one place (index.blade.php). I'm now refactoring, extracting my css code into it's own file (that lives in public/css/custom.css) and also using bootstrap.

I'm having issues with my css now and it is not working correctly. For example, when trying to customize .col-md-4 in my css file, it doesn't work until it is resized to a smaller window. How do I make changes to all size windows/displays?

I'm calling the css file from index.blade.php with <link href="{{ asset('css/custom.css') }}" rel="stylesheet" type="text/css" > in the <head> section.

Again, when moving the css code to another file, the css no longer works correctly when it is desktop size, only a smaller window/display size. Also, my fonts are working so I just put in my index.blade.php file in the <style> section.

Do I need to be using laravel elixir or anything to get the css file working correctly? What am I doing wrong? Thanks in advance!



via Chebli Mohamed

Phpunit testing Laravel 5.1 restful controller

I have been stuck on that issue for a little while, no other question on SO helped me.

I am using Laravel 5.1 and phpunit to test a restful controller. My testing code looks as such:

$this->post('/api/book', [ 'title' => 'my book'])
  ->assertResponseOk();

And the target controller has, among others, the following code:

Log::debug('title: ' . $request->json('title'));

i.e. on the testing side I expect to use the TestCase::post() method to send a request and on the server side I expect to use the Request::json() method to read from the request. However when I look at the logs I see the following empty string

[2015-10-31 17:26:01] testing.DEBUG: title:   

This is showing that either my testing code is not setting the right data in the request or that my server code is not reading the request properly. By the way, the server is failing a bit further as well, reflecting the missing title value in the logs.

I am also using a Firefox plugin, RESTClient, to manually test my web app and I had to set properly the body (using double-quotes around the title key, respecting strictly the JSON specs) to make sure the server code work. So the exact format is a trail I followed, without success so far.

So my question is, what is the most recommended code to use for a RESTful controller on the testing and on the server sides, in Laravel 5.1?



via Chebli Mohamed

Phpunit Laravel Flash Message Error

I have the following test class which I'm trying to test for user registration:

 public function a_user_may_register_for_an_account_but_must_confirm_their_email_address()
{
    $this->visit('register')
         ->type('John Doe', 'name')
         ->type('john.doe@example.com', 'email')
         ->type('password', 'password')
         ->press('Register');

    $this->see('Please confirm your email address')
        ->seeInDatabase('users', ['email' => 'john.doe@example.com', 'verified' => 0 ]);

}

But I'm getting the following error message:

' matches PCRE pattern "/(Please confirm your email address|Please confirm your email address)/i".

My controller method is as follows:

public function postRegister(Request $request, AppMailer $mailer)
{
    $validator = $this->validator($request->all());

    if ($validator->fails()) {
        $this->throwValidationException(
            $request, $validator
        );
    }

    $user = $this->create($request->all());

    $mailer->sendEmailConfirmationTo($user);

    flash()->info('Please confirm your email address');

    return redirect()->back();
}

I have a layout.blade view as follows:

<body>
     @include('layouts.partials.nav')
     @include('flash::message')
     @yield('content')
     @include('layouts.partials.footer')
</body>

My registration.blade view is as follows:

@extends('layout.layout')

@section('content')
   <!-- registration form -->

@endsection

When I register using the the browser the flash message displays fine and all is working. Why is php unit then throwing this error?



via Chebli Mohamed

Is it possible to combine a dom-repeat on a platinum service worker?

I want to provide a user the ability to cache up to 2,600+ items, by groupings (categories of book, individual books, or possibly even just chapters of a certain book if they don't want the whole book). It is not possible, as far as I can tell, to precache all of these items because there are 2,600+ of them, and will be more in the future - the service worker will timeout with under a couple hundred. And since service workers either get all or none on install (if I understand correctly), do I need to use multiple services workers (with different ids?), or am I thinking about this wrong?

What I am thinking is something like...

<iron ajax></iron-ajax>
<template is="dom-repeat" items="...">
<platinum-sw-register auto-register clients-claim skip-waiting>
    <platinum-sw-cache default-cache-strategy="fastest"
        cache-config-file="../someGenerator.php"></platinum-sw-cache>
</platinum-sw-register>

In other words:

  1. Get a list of wanted URLs via iron-ajax (based upon what the user enables for cache)
  2. Iterate through the URLs as groups via dom-repeat
  3. Create a service worker with a customized cache-config for the URL group
  4. Repeat 2 and 3 until done, then present a toast

That someGenerator.php would return a JSON config setup for the particular group of URLs.

My app is a single page app - with neon-animated-pages - one page representing categories, one for book listings, one for table of contents for each book, and then one of each the chapter contents. All of the data is obtained via iron-ajax.

Here are some links to demonstrate the issues:

The App

A large non-functional cache-config generated

I suspect, in order to not have service workers errors due to redundancy, or overwrite existing caches, I will need to assign individual ids, and include them in the generated cache-configs. Does that sound right?



via Chebli Mohamed

Why does Laravel create a new session after a GuzzleHttp POST request to the same subdomain?

I'm trying to make a post request to the same subdomain with GuzzleHttp in a Laravel 5.1 installation, but as a response the login page is returned, showing that a new Session has been created in the request. The current session is not affected.

Why does Laravel create a new session?

In session.php I have the following values:

'driver' => env('SESSION_DRIVER', 'file'),
'lifetime' => 120,
'expire_on_close' => true,
'files' => storage_path('framework/sessions'),
'cookie' => 'admin_mydomain_com_session',
'path' => '/',
'domain' => 'admin.mydomain.com',
'secure' => false

In my controller I use the following code to make the request:

// Create headers
$headers = array(
    'X-CSRF-Token' => csrf_token()
);

// Create data
$data = array(
    'param' => 'param',
    '_token' => csrf_token()
);

// Create a POST request
$client = new Client();
$res = $client->request('POST', 'http://ift.tt/1WncRvO',
    array(
        'headers' => $headers,
        'form_params' => $data
    )
);
$statusCode = $res->getStatusCode();
$body = $res->getBody();

echo $body; // Shows me the login page



via Chebli Mohamed

Creating edit function in the same controller laravel

So I have a create function in my controller as shown below and my routes is as such, my question is is there a way for me to put a condition to different create and edit in the same function as both have quite similar coding. Can someone enlighten me pls?

class ManageAccountsController extends Controller
{
    public function index() {
        $users = User::orderBy('name')->get();
        $roles = Role::all();

        return view('manage_accounts', compact('users', 'roles'));
    }

    public function update()
    {
            // process the form here

    // create the validation rules ------------------------
        $rules = array(
        'name'             => 'required',                        // just a normal required validation
        'email'            => 'required|email|unique:users',     // required and must be unique in the user table
        'password'         => 'required|min:8|alpha_num',
        'password_confirm' => 'required|same:password',           // required and has to match the password field
        'mobile'           => 'required', 
        'role_id'          => 'required'
        );

    // do the validation ----------------------------------
    // validate against the inputs from our form
        $validator = Validator::make(Input::all(), $rules);

    // check if the validator failed -----------------------
        if ($validator->fails()) {

        // redirect our user back to the form with the errors from the validator

            $input = Input::except('password', 'password_confirm');

            $input['autoOpenModal'] = 'true'; //Add the auto open indicator flag as an input.
            return redirect()
            ->back()
            ->withInput($input)
            ->withErrors($validator);

        } else {
        // validation successful ---------------------------

        // user has passed all tests!
        // let user enter the database

        // create the data for our user
            $user = new User;
            $user->name     = Input::get('name');
            $user->email    = Input::get('email');
            $user->password = Hash::make(Input::get('password'));
            $user->mobile   = Input::get('mobile');
            $user->role_id  = Input::get('role_id');

        // save our user
            $user->save();

        // redirect ----------------------------------------
        // redirect our user back to the form so they can do it all over again
            Session::flash('flash_message', 'User successfully added!');

            return redirect()->back();

        }
    }
}

routes.php

Route::get('manage_accounts', 'ManageAccountsController@index');
Route::post('manage_accounts', 'ManageAccountsController@update');



via Chebli Mohamed

why is the hash-method in the seeder different from the hash-method in the controller? Laravel 5.1

In my seeder I have hashed my code like this :

'validCode' => Hash::make('1110578abc')

it gives this result in the database : $2y$10$GaKhhxrMNCnzr

When I'm hashing the same code by input in my controller it gives a different value

Controller :

dd(Hash::make(Input::get('code')));

(I typed in 1110578abc in this input field.)

It gives me this value :

$2y$10$xxVU78CphJEGOOTT1teNY.LeLb7kBjDvP9Npbf1h4.T4HDtuIFD16

Can annyone explain why this is not the same value? For my application I would like to have the same value from my database, in my controller from the input field, to check if they match.



via Chebli Mohamed

vendredi 30 octobre 2015

Session is not created during login using Laravel 5.1

When I login to the system using Laravel 5.1 I logged in but session is not created I don't know what's the problem. I'm using AuthController with a little customization. This is the controller:

 public function __construct()
{
    $this->middleware('guest', ['except' => 'getLogout']);
}

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

public function postLogin(Request $request)
{
    $this->validate($request, [
        'username' => 'required|alpha_num|max:255',
        'password' => 'required|between:4,10',
    ]);

    if (\Auth::attempt($request->only(['username', 'password']))) {
        return redirect()->intended('/events');
    }
    return redirect()->back()->withInput()->with('error', 'Username Or Password is wrong!');
}

And this is the middleware

class UserMiddleware

{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if ($request->input('role') == 'admin') { return redirect('/dashboard'); } elseif ($request->input('role') == 'faculty') { return redirect('/events'); } elseif ($request->input('role') == 'student') { return redirect('/news'); }

    return $next($request);
}

}



via Chebli Mohamed

How to get reference table data in Laravel 5.1

I created a Model Account with accountgroup_id which refer from Account_group Model. Then I call it from route like this

 Route::get('test', function () {
    return \App\Account::get()->account_group;
  });

Account Model has belogsto Relationship with Account_group

 class Account extends Model
 {
     protected $fillable = ['accountgroup_id', 'accountno', 'accountname','address','contactno'];

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

Account_group Model has hasMany relationship with Account

class Account_group extends Model
{
   protected $fillable =['name','under'];
   public function account()
   {
    return $this->hasMany('App\Account','accountgroup_id');
   }
 }

But after calling the route; I got following error.

Undefined property: Illuminate\Database\Eloquent\Collection::$account_group



via Chebli Mohamed

Post to multiple accounts on twitter using API. getting duplicate status error.

Trying to post to twitter using laravel and this twitter API package. Im using a foreach loop to grab each of the account tokens and post but I keep getting the error Duplicate status because it seems like its not changing the tokens before its posting to twitter. I've tried to refresh the page and the break the connection, still getting the error.

here is my foreachloop

foreach ($post['accountsToPost'] as $accountToPost) {
            $uniqueProfile= DB::table('profiles')->where('social_media_id', $accountsToPost)->first();
            $new_token = [
                'oauth_token'        => $uniqueProfile_test->oauth_token,
                'oauth_token_secret' => $uniqueProfile_test->oauth_secret,
                'x_auth_expires'     => $uniqueProfile_test->x_auth_expires,
            ];

            Session::forget('access_token');
            Session::put('access_token', $new_token);
            Twitter::postTweet(['status' => $post['post_text'], 'format' => 'json']);
            Session::flash('flash_message', 'Success! Your post has been sent.');
        }

Into the foreach loop im passing in 1. The social media I.D 2. The Oauth, secret tokens 3. The content to post

When I track the tokens using echo it seems to be getting all the right tokens but just not when posting to twitter. Could it be a connection issue? thats its not refreshing the connection for each account?



via Chebli Mohamed

how i can open admin page in other tab with redirect::to?

how i can open admin page in other tab (target blank) when user login?

In my controller after validate return this:

return Redirect::to('/adminpanel');



via Chebli Mohamed

composer dump-autoload doesn't add psr-4 classes

I'm using laravel 5.1. I've added my custom namespace inside the app/Library and namespaced like projectname.

{
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Library\\": "app/Library/"
        }
    }
}

Whenever I create anything with make command I get ReflecitonError that the class does not exist. I thought Laravel uses composer dump-autoload after the make command, then I ran composer dump-autoload and got that the classes inside the Library folder don't get included inside the autoload_classmap.php file. Then I ran composer dump-autoload -o got that the files inside my namespace were included.
What was wrong? What can be the possible solution?



via Chebli Mohamed

Nginx Configuration for Laravel Project

I keep getting 403 Forbidden

Here is my setting on :/etc/nginx/sites-available/default

default

server {

    listen 80 default_server;
    server_name default;

    root /usr/share/nginx/portal/public;

    #root /usr/share/nginx/html; #<--- Original one

    index index.html index.htm index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

}


Result enter image description here

It also downloaded a file name download - each time I refresh. That file has no extension.

I open it up, it contains

download

<?php

/**
 * Laravel - A PHP Framework For Web Artisans
 *
 * @package  Laravel
 * @author   Taylor Otwell <taylorotwell@gmail.com>
 */

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels nice to relax.
|
*/

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

/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/

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

/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
|
*/

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

$response->send();

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


Any hints/suggestions on this will be a huge help !



via Chebli Mohamed

How to pass parameter middleware laravel 5.1

I have read many ideas about how to pass parameter in middleware but if there is any possibilities to get full example about that



via Chebli Mohamed

Select data by status coloum in laravel 5

IN Custom php code

$select_query = "select * from admin where Stutes = '1' order by ID asc";

How we can embed this code in my this laravel 5 code

public function index()
{   
    $books=Book::all();
    return view('books.index', compact('books'));
}



via Chebli Mohamed

JavaScript parse Error

I am Using laravel 5.1 PHP framework, I am using a sign chart from a javaScrpt, But when i Send data from controller with ' (single cote) but JavaScript Parse as some undefined value $data_B_Temp = "{x : new Date('".$piecesTime[$dataLength]."'), y :".$pieces[$dataLength]."}";

this variable will make a graph point input as

$(function () {

var chart = new CanvasJS.Chart("TempChart",
{


  axisX:{
    title: "time",
    gridThickness: 2,
    interval:1,
    intervalType: "hour",
    valueFormatString: "hh TT K",
    labelAngle: -10
  },
  axisY:{
    title: "distance"
  },
  data: [
  {
    type: "line",
   dataPoints:[{{$data_B_Temp }}]

  }
  ]
});

$("#TempChart").CanvasJSChart(chart.render());

});`

But the javascript executes as

`dataPoints:[{x : new Date(&#039;2015-10-30 18:16:08&#039;), y :38.5}]`

i'm confused &#039 is coming?, how to solve it?



via Chebli Mohamed

Scaffolding library for laravel 5.1

i'm trying to build a new app in Laravel 5.1 and i want to use some scaffolding. I found this pack: http://ift.tt/1NFDjcG and it fits to my need.

But it seems not compatible with Laravel 5.1 and no longer mantained, can you suggest another scaffold library? I'd like it to generate also basic graphic with bootstrap (like this one).

Thank you in advance



via Chebli Mohamed

Laravel 5.1 - return eloquent model with multiple relationships

I have the following models Show, Presenter, Image.

Shows can have multiple presenters. Presenters have one image.

I can do this to get a presenter with their image:

$presenter = Presenter::with('image)->find(1);

And I can do this to get a show with presenters:

$show = Show::with('presenters')->find(1);

Is there a way I can return a show with presenters and their image in one statement?



via Chebli Mohamed

Laravel ACL: Policy Class not being read

So in AuthServiceProvider I am doing following:

namespace App\Providers;

use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;


class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        \App\Post::class => PostPolicy::class
    ];

    /**
     * Register any application authentication / authorization services.
     *
     * @param  \Illuminate\Contracts\Auth\Access\Gate  $gate
     * @return void
     */
    public function boot(GateContract $gate)
    {
        parent::registerPolicies($gate);

    }

PostPolicy

namespace App\Policies;

use App\Post;
use App\User;

class BriefPolicy
{
    /**
     * Create a new policy instance.
     *
     * @return void
     */
    public function __construct()
    {
    }
    public function view(User $user)
    {
        dd('he was here');//This line NEVER gets executed.
        return $user->type === 'user';
    }
}



via Chebli Mohamed

Keep modal open and showing error laravel

Yes, I saw the other two post on this question unfortunately I still could not get it working, my modal still closes, how o I keep my modal open while showing the erors? am I missing out on something?

Controller:

// check if the validator failed -----------------------
        if ($validator->fails()) {

        // get the error messages from the validator
            $messages = $validator->messages();

        // redirect our user back to the form with the errors from the validator
            $input = Input::except('password', 'password_confirm'); //Get all the old input except password.
            $input['autoOpenModal'] = 'true'; //Add the auto open indicator flag as an input.
            return Redirect::back()
            ->withErrors($validator)
            ->withInput($input);

        } else {

Blade.php:

  <!-- Modal -->
  <div id="register" class="modal fade" id="remoteModal" role="dialog">
     <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
           <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal">&times;</button>
              <h4 class="modal-title">New User</h4>
          </div>
          <div class="modal-body">
              <form class="form-horizontal" role="form" method="POST" action="/manage_accounts" novalidate>
               <input type="hidden" name="_token" value="{{ csrf_token() }}">
               <div class="form-group">
                <label class="control-label col-sm-3" for="name">Username:</label>
                <div class="col-sm-5"> 
                   <input type="text" class="form-control" type="hidden" id="name" name="name" placeholder="Enter username">
                   @if ($errors->has('name')) <p class="help-block">{{ $errors->first('name') }}</p> @endif
               </div>
           </div>
           <div class="form-group">
            <label class="control-label col-sm-3" for="password">Password:</label>
            <div class="col-sm-5"> 
               <input type="password" class="form-control" type="hidden" id="password" name="password" placeholder="Enter login password">
           </div>
       </div>
       <div class="form-group">
        <label class="control-label col-sm-3" for="password_confirm">Confirm Password:</label>
        <div class="col-sm-5"> 
           <input type="password" class="form-control" type="hidden" id="password_confirm" name="password_confirm" placeholder="Re-type password again">
       </div>
   </div>
   <div class="form-group">
    <label class="control-label col-sm-3" for="email">Email:</label>
    <div class="col-sm-5"> 
       <input type="email" class="form-control" type="hidden" id="email" name="email" placeholder="Enter email address">
   </div>
</div> 
<div class="form-group">
    <label class="control-label col-sm-3" for="mobile">Phone Number:</label>
    <div class="col-sm-5"> 
       <input type="hpnum" class="form-control" type="hidden" id="mobile" name="mobile" placeholder="Enter handphone number">
   </div>
</div>
 <!--<div class="form-group">
    <label class="control-label col-sm-3" for="officeEx">Office Extension:</label>
        <div class="col-sm-5"> 
            <input type="officeEx" class="form-control" id="officeEx" placeholder="Enter office extension">
        </div>
    </div> -->                                                                                                                     
   <div class="form-group">
    <label class="control-label col-sm-3" for="role_id">Role:</label>
    <div class="col-sm-5">
        <select class="form-control" type="hidden" id="role_id" name="role_id">
            @foreach ($roles as $role)
            <option value="{{ $role->id }}">{{ $role->role_description }}</option>
            @endforeach
        </select>
    </div>
</div>
<div class="form-group"> 
    <div class="col-sm-offset-3 col-sm-5">
       <button type="submit" class="btn btn-default">Register</button>
   </div>
</div>
</form>
</div>
<div class="modal-footer">
  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

<script type="text/javascript">
     if ({{ Input::old('autoOpenModal', 'false') }}) {
        //JavaScript code that open up your modal.
        $('#remoteModal').modal('show');
    }
</script>



via Chebli Mohamed

Laravel 5.1 debugbar not showing in virtual host

I installed fresh laravel 5.1 Added Debugbar from this http://ift.tt/17t61JL Its working fine in localhost/laravel/public but not working in virtual host like http://laravel.dev Please help



via Chebli Mohamed

Laravel on sorting related model?

I know from laravel documentation that I can do eager loading like:

$records = (new Route)->with('country')->get();

But when I execute this:

    $records = (new Route)->query()->with('country')->orderBy('country.name', 'asc')->paginate();

I get this error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'country.name' in 'order clause' (SQL: select * from `routes` order by `country`.`name` asc limit 2 offset 0)

How I can sort on related model ? How can I force laravel to load joined tables?



via Chebli Mohamed

Tutorial on how to setup multiple laravel 5.1 apps in one project

I am currently working on a Laravel 5.1 project which involves a public section and a admin section. When googling around the issue I was having, I came across this stack post managing user role log in. Where the first post recommends.

Admin and Users in the same laravel app is a bad idea simply because the app will share the same session and storage information. There will be a myriad of egde cases that will cause information to bleed through any logic "walls" you set up and you'll end up spending way too much time patching those bleeds. What you really want to do is set up separate laravel applications for each: admin.project.com & project.com. That way you get two separate sessions and storage. All you need to do is ensure that the databases you need are setup in both database.php config files. You can even host BOTH projects on the same server with separate deployments, listening to different ports. TRUST ME this is the best way to go.

Could someone explain in detail how it could be done? I mean how should I set up my project. I know It is easy for them to share the same DB and setting up that would easy. First question, how can I have URLs admin.mysite.com as my admin section and www.mysite.com as my public section for my 2 apps Also how to set it up in Azure as a web app? I got my one app I currently have working on Azure ( no 5.1 guides on the internet, got it deploying somehow).

So could someone explain in detail how the project setup should like and how it should be done? Could not find guides for Laravel 5.1 and since 5.1 setup is different from 5 and 4.* I'm not sure how to continue.



via Chebli Mohamed

Input::get() retrieving variable unique id instead of value laravel

I created a form and have a dropdown option which shows a list of option, after selecting the selected value it gets the description value instead. However I would like to retrieve the unique id instead of the description, how can I do so?

In my view.blade.php,

<div class="form-group">
    <label class="control-label col-sm-3" for="role_id">Role:</label>
    <div class="col-sm-5">
        <select class="form-control" id="role_id" name="role_id">
            @foreach ($roles as $role)
            <option>{{ $role->role_description }}</option>
            @endforeach
        </select>
    </div>
</div>

Then in my controller,

 // create the data for our user
            $user = new User;
            $user->name     = Input::get('name');
            $user->email    = Input::get('email');
            $user->password = Hash::make(Input::get('password'));
            $user->mobile   = Input::get('mobile');
            $user->role_id  = Input::get('role_id');

        // save our user
            $user->save();

Is this part of the code sufficient enough for my explanation? Or shoould I show you the entire code instead.



via Chebli Mohamed

Laravel 5.1 Ajax call for 'Like' system not happening

I am building an application where users can upload projects. I am implementing a system where users can 'Like/Unlike' other projects. I am trying to use an AJAX call to save likes. Users are able to like projects on the detail page of a project (/projects/{id})

I have a table users, projects and likes. My plan is to save the likes in the likes table obviously so a record looks like this: id, user_id, project_id. In the future I can do a COUNT query and find out how many likes each project has, etc.

Currently nothing happens when I click on the like button I get no errors, nothing happens.

My files: Routes.php

Route::get('/', 'LikeController@index');
Route::post('projects/{id}', 'LikeController@like');

LikeController.php:

public function like()
{
    if(Request::ajax()) {
        $data = Input::all();
        print_r($data);die;
    }
}

My view: show.blade.php

{!! Form::open(array('url'=>'projects/'.$project->id.'/like','method'=>'POST', 'id'=>'myform')) !!}
{!! Form::button('Like', array('class'=>'send-btn')) !!}
{!! Form::close() !!}

My AJAX call

<script type="text/javascript">
    $(document).ready(function(){
        $('.send-btn').click(function(){
            $.ajax({
                url: 'projects',
                type: "post",
                data: {'user_id': $('input[name=user_id]').val(), 'project_id': $('input[name=project_id]').val()},
                success: function(data){
                    alert(data);
                }
            });
        });
    });
</script>



via Chebli Mohamed

Laravel 5.1 - How view()->share works?

I am developing a web application where the footer lists latest and most popular posts. I also use this data at some other places as well (for e.g. homepage slider shows popular posts etc).

I tried exposing this data to all my views via view()->composer and also tried via view()->share from boot() method in AppServiceProvider.php

This is my code via view()->composer

public function boot()
{
    view()->composer('*', function ($view) {
                $popular = Post::with('likedby')->published()->get()
                          ->sortByDesc(function($item){ 
                                      return $item->likedby->count();
                           })->take(4);

                $popular->load('comment');

                $latest = Post::orderBy('created_at','desc')
                          ->published()->get()->take(4);

                $latest->load('comment','likedby');


                $view->with(compact('popular','latest'));

    });

}

This is my code via view()->share

public function boot()
{
    $popular = Post::with('likedby')->published()->get()
                              ->sortByDesc(function($item){ 
                                          return $item->likedby->count();
                               })->take(4);

    $popular->load('comment');

    $latest = Post::orderBy('created_at','desc')
                         ->published()->get()->take(4);

    $latest->load('comment','likedby');


    view()->share(compact('popular','latest'));
}

Basically, the queries are same.

I listen to the query event in routes.php

Event::listen('illuminate.query', function($query)
{
    var_dump($query);
});

I understood how view()->composer works - it basically run the callback function on every view [infact it calls the function multiple times if there are subviews e.g. @include('comments.list') ]

However, view()->share didn't show any queries, I am guessing that it got executed before I registered to listen for query events (in routes.php).

So, how view()->share really works and when it is called if I put it in boot() of AppServiceProvider.php? Are these variables stored as global variables?

Is there a way to listen to the query event in this case so I can properly test caching?



via Chebli Mohamed

Laravel 5.1 eloquent relations

I was implementing a quiz system using Laravel 5.1

I was facing some problems with inserting and updation of data in questions table

MySQL Schema

Subjects  (Table 1)
________________
Subject_ID (Primary Key) auto_increment,
Subject_Name


Questions (Table 2)
________________
Question_ID (Primary Key) auto_increment,
Question,
Options_1,
Options_2,
Options_3,
Options_4,
Answer,
Subject_Id (Foreign Key refers to Primary Key of Subjects Table [Table 1])

While inserting question in the questions table, I was unable to get the Subject_Id from Subjects table

I was implementing the following query using Laravel

insert into questions values("", "Question", "Option 1", "Option 2", "Option 3", "Option 4", "Answer", "select subject_id from subjects where subject_name = $subject_name");

$subject_name is the variable that fetches the subject name from the user interface



via Chebli Mohamed

Unable to save select box options in Laravel 5.1

I am working on my first project using Laravel 5.1. Uses a selectbox in a form.

{!!Form::select('animal_parent[]', array('1' =>  'opt1',  '2' =>  'opt2',  '3' => 'opt3', '4' => 'opt4',), null, ['id' => 'animal_parent', 'disabled' => 'disabled', 'multiple' => 'multiple', 'class' => 'form-control'])!!}

Selection limited to two options which need to saved in two columns, 'male_parent' and 'female_ parent' of the 'animal' table.

There are no 'male_parent' and 'female_ parent' element names in the form. Similarly no 'animal_parent' field in 'animal' table.

Values are set as expected in the code given below. However, the insert command does not reflect the newly set values and throws an error.

"ErrorException in helpers.php line 671: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array."

Any help would be much appreciated.

First attempt using mutators

public function setMaleParentAttribute()
    {

        $parent = Input::get('animal_parent');
        $this->attributes['male_parent'] = intval($parent[0]);
    }

    public function setFemaleParentAttribute(AddAnimalRequest $request)
    {
        $parent = Input::get('animal_parent);
        if (isset($parent[1])) {
           $this->attributes['female_parent'] = intval($parent[1]);
        } else {
            $this->attributes['female_parent'] = intval($parent[0]);
        }
     unset($request->animal_parent);

Second attempt using the store() method in the controller.

            $animal = new Animal($request->all());
            $parent = Input::get('animal_parent');

            $animal['male_parent'] = intval($parent[0]);
            if (isset($parent[1])) {
                $animal['female_parent'] = intval($parent[1]);
            } else {
                $animal['female_parent'] = intval($parent[0]);
            }

            unset($request->animal_parent);
            Auth::user()->animals()->save($animal);
            return redirect('animals');



via Chebli Mohamed

Get the prefix in Laravel 5.1 -Dingo/Api

I am using Laravel 5.1 and Dingo/Api. Is there a way to get the route prefix in it? I tried the getLastGroupPrefix() but it always returns null

Here's my code

BaseController :

public function isAdminRequest()
    {
        return Route::getLastGroupPrefix();
    }

routes :

$api->group(array('prefix' => 'admin'), function($api)
    {
        $api->resource('users', "App\Http\Controllers\UsersController");
    });

and I'm trying to use it in my UsersController by doing so

    public function index()
    {
        return $this->isAdminRequest();
    }

But I just get a blank page.



via Chebli Mohamed

jeudi 29 octobre 2015

Laravel: Gate::denies not working

So I am trying to use Laravel Authorization. For here I did following:

  • Laravel updated to *.1.19
  • Create The Policies Directory
  • Facade defined in app.php

I created a Policy and put following code in it:

//Allow users of type 'users`    
public function view(User $user)
        {
            dd('he was here'); // Not coming here
            return $user->user_type === 'user';
        }

In Controller I did:

if (Gate::denies('view')) {
            dd('Sorry Bud not allowed');
        }

Thing is, it is always getting into blocks 'Sorry Bud not allowed'.

Am I missing some step or something else?



via Chebli Mohamed

Where to put data for select boxes in Laravel?

If I have table in database like this:

users
    id
    username
    status

and status can be:

status 0 - not active 1 - active 2 - banned

where should I put statuses, i have some possibilities:

  1. in repository pattern for users
  2. in User Eloquent class
  3. in helpers
  4. in database (sometimes I would create 50 more tables for this and I dont think this is good idea)

?



via Chebli Mohamed

APNS with PHP (Apple Push Notification Service)

How can I integrate the new Apple Push Notification Service in a PHP backend?

http://ift.tt/1JNPiFl



via Chebli Mohamed

Laravel seeding - unique pairs of user and teacher IDs

I am using database migration and seeding in Laravel 5.1.

Migration

public function up()
{
    Schema::create('teachers', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->integer('teacher_id')->unsigned();
        $table->boolean('disable')->default(0);
        $table->timestamps();

        $table->unique(['user_id', 'teacher_id']);

        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->foreign('teacher_id')->references('id')->on('users')->onDelete('cascade');
    });
}

*** user_id and teacher_id must be unique together.

Model Factory

$factory->define(App\Teacher::class, function ($faker) {
    return [
        'user_id'           => $faker->numberBetween(1, 59),
        'teacher_id'        => $faker->numberBetween(1, 59),
    ];
});

I set up the seeder for producing 500 teacher relational in DatabaseSeeder.php: factory(App\Teacher::class, 500)->create();

but i got this error:

[PDOException] 
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '10-11' for key 'teachers_user_id_teacher_id_ 
unique'

As you can see, the *** (unique property) caused the error. is there any way to fix it? What is your idea?



via Chebli Mohamed

Nested View not getting data from parent controller in Laravel 5.1

I'm building an Employee Management system and The employee part works good but when i try to create for family members for an employee i have a problem. I was hoping i can create a family member for an employee in such a way localhost/mysite/employees/5/families/create

Here are my files P.S - I have omitted some of the code which i thought was irrelevant. For example, there are more than 30 employee fields that i save. For this question i just displayed the FirstName

routes.php

Route::resource('employees', 'EmployeesController');
Route::resource('employees.families', 'FamiliesController');

EmployeesController.php

<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Employee;
use Illuminate\Http\Request;
use DB;
use App\Http\Controllers\Controller;


class EmployeesController extends Controller
{

    public function index()
    {              
        //Stuff that works well on employees/index
    }

    public function create()
    {
        //Stuff that works well on employees/create
    }

    public function store(Request $request)
    {
        //Stuff that works well     
    }


    public function show(Employee $employee)
    {
        $employee=Employee::find($EmployeeID);
        return view('employees.show', compact('employee'));
    }


    public function edit($EmployeeID)
    {
        $employee=Employee::find($EmployeeID);          
        return view('employees.edit',compact('employee'));
    }


    public function update(Request $request, $EmployeeID)
    {
         //Stuff that works well on employees/edit
    }

}

Employee.php (Model)

<?php

namespace App;

use Illuminate\Database\Eloquent\SoftDeletes;

use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];

    protected $primaryKey = 'EmployeeID';

    protected $fillable=[
        'Name'
    ];

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

FamilyController.php (For now i only posted the index and create methods)

<?php

namespace App\Http\Controllers;

use App\Employee;
use App\Family;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class FamiliesController extends Controller
{
    public function index(Employee $employee)
    {
        return view('families.index', compact('employee'));
    }

    public function create(Employee $employee)
    {
        return view('families.create', compact('employee'));
    }

}

Family.php (Model)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Family extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];

      protected $primaryKey = 'FamilyID';

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

Result from php artisan route:list

+--------+----------+------------------------------------------------+----------------------------+--------------------------------------------------+------------+
| Domain | Method   | URI                                            | Name                       | Action                                           | Middleware |
+--------+----------+------------------------------------------------+----------------------------+--------------------------------------------------+------------+
|        | GET|HEAD | employees                                      | employees.index            | App\Http\Controllers\EmployeesController@index   |            |
|        | POST     | employees                                      | employees.store            | App\Http\Controllers\EmployeesController@store   |            |
|        | GET|HEAD | employees/create                               | employees.create           | App\Http\Controllers\EmployeesController@create  |            |
|        | PATCH    | employees/{employees}                          |                            | App\Http\Controllers\EmployeesController@update  |            |
|        | PUT      | employees/{employees}                          | employees.update           | App\Http\Controllers\EmployeesController@update  |            |
|        | DELETE   | employees/{employees}                          | employees.destroy          | App\Http\Controllers\EmployeesController@destroy |            |
|        | GET|HEAD | employees/{employees}                          | employees.show             | App\Http\Controllers\EmployeesController@show    |            |
|        | GET|HEAD | employees/{employees}/edit                     | employees.edit             | App\Http\Controllers\EmployeesController@edit    |            |
|        | GET|HEAD | employees/{employees}/families                 | employees.families.index   | App\Http\Controllers\FamiliesController@index    |            |
|        | POST     | employees/{employees}/families                 | employees.families.store   | App\Http\Controllers\FamiliesController@store    |            |
|        | GET|HEAD | employees/{employees}/families/create          | employees.families.create  | App\Http\Controllers\FamiliesController@create   |            |
|        | PUT      | employees/{employees}/families/{families}      | employees.families.update  | App\Http\Controllers\FamiliesController@update   |            |
|        | DELETE   | employees/{employees}/families/{families}      | employees.families.destroy | App\Http\Controllers\FamiliesController@destroy  |            |
|        | GET|HEAD | employees/{employees}/families/{families}      | employees.families.show    | App\Http\Controllers\FamiliesController@show     |            |
|        | PATCH    | employees/{employees}/families/{families}      |                            | App\Http\Controllers\FamiliesController@update   |            |
|        | GET|HEAD | employees/{employees}/families/{families}/edit | employees.families.edit    | App\Http\Controllers\FamiliesController@edit     |            |
|        | GET|HEAD | employees/{id}/delete                          |                            | App\Http\Controllers\EmployeesController@delete  |            |
+--------+----------+------------------------------------------------+----------------------------+--------------------------------------------------+------------+

When i navigate to http://localhost/mysite/public/employees/1/families/create i can see the create form but it's not getting the employee data. i did a vardump of $employee on that page and i was expecting to see the data for EmployeeID = 1 (as you can see from the url), but it was blank. Funny thing is that it's not throwing an error, it receives the $employee data passed from the controller but it a blank data.

So what could be the problem?



via Chebli Mohamed

Is there any benefit to learn Laravel while I'm well familiarized with symfony2 already?

I'm using symfony2 since one year and I like it too much but I just get a nice job and two of my collegues are using Laravel then I fear that the supervisor (one of my collegue) decide that we work with Lavarel because this is what he's using as he doesn't not know symfony2, it'll be not easy for me to convence him. My question is: once Laravel framework has been build on some of the symfony's component then does it make it easy for me to learn Laravel ? and does laravel have reusables component like "bundle" in symfony2 ? it I take 10 days of learning I'm able to know Laravel well ?



via Chebli Mohamed

Laravel 5.1 UrlGenerator route not defined error

I have an app built with Laravel 5.1. I'm using Form::open using a route_name to generate the url to post the form to as well as creating links by defining route and using the UrlGenerator. The issue is that I have some buttons/links created for display purposes and do not have pages created yet.

I get a route not defined error with stack trace going back to UrlGenerator line 296. I'm wanting to set up something so that the error does not display. Instead, I would like a link to be generated to the pre-defined page that I have created saying that the feature the user clicked on is not yet developed.

I thought about doing something similar to a 404 error, but the issue is that the existing page (the page the link or button lives on) is not being displayed, not just that route is missing.



via Chebli Mohamed

CLNDR.js templating with VUE.js or Laravel Blade

Is it possible to template clndr.js using vue.js or laravel blade? Currently the example uses underscore.js as follows:

<div id="mini-clndr"></div>

 <script id="calendar-template" type="text/template">
  <div class="controls">
    <div class="clndr-previous-button">&lsaquo;</div><div class="month"><%= month %></div><div class="clndr-next-button">&rsaquo;</div>
  </div>

  <div class="days-container">
    <div class="days">
      <div class="headers">
        <% _.each(daysOfTheWeek, function(day) { %><div class="day-header"><%= day %></div><% }); %>
      </div>
      <% _.each(days, function(day) { %><div class="<%= day.classes %>" id="<%= day.id %>"><%= day.day %></div><% }); %>
    </div>
  </div>
 </script>

The javascript code:

$('#mini-clndr').clndr({
  template: $('#calendar-template').html(),
  adjacentDaysChangeMonth: true 
});   

The closest I've come across is an example using angular.js

I'd class myself a beginner at using vue.js. Are there any vue.js or laravel blade experts who can guide me on how to template clndr.js using vue.js or blade? Some snippets of code would be helpful to get me started.

I'm struggling on how I'd render the template. The clndr.js documentation give an example as follows:

var precompiledTemplate = myRenderingEngine.template( $('#my-template').html() );

$('#my-calendar').clndr({
  render: function(data) {
    return precompiledTemplate(data);
  }
});

How can you do this in vue.js or laravel blade? Any suggestions would help.



via Chebli Mohamed

Laravel 5.1 formfacade can't get value from select

I have created a form to change the user name and its role in the website.

@extends('layout/layoutAdmin')
@section('content')
<div>
  <h1>{{ $user -> name }}<h1>
  <p>{{ $user -> email }}<p>
</div>
{!! Form::model($user, ['url' => 'admin/menu/user_profiles/' . $user->id,  'method' => 'PATCH']) !!}
<div class="row">
<div class ="form-group">
    {!! Form::label('name', 'Name:') !!}
    {!! Form::text('name', $user->name,['class' => 'form-control']) !!}
</div>
<div class="form-group">
   {!! Form::label('role', 'Role:') !!}
   {!! Form::select('role', array('admin' => 'admin', 'super_admin' => 'super admin',
   'super_researcher' => 'super researcher', 'researcher' => 'researcher',
   'consultant' => 'consultant', 'user' => 'user'), $user->role)
    !!}
 </div>
 <div class="form-group col-xs-8 col-md-7">
   {!! Form::submit('Update', ['class' => 'btn btn-primary']) !!}
 </div>
</div>
{!! Form::close() !!}

@stop

Everything is correct with the controller and I can change the name just fine, but I cannot save a new value for the role. it always stays the same. Could anyone tell me how to save the role value?



via Chebli Mohamed

laravel 5.1 - Dynamically create Class object based on string

i want to create object of class base on string which come from URL parameter.

for example :

 http://localhost/CSWeb/api/search/Slideshare

in above URL Slideshare is parameter which get in apiController->indexAction.

apiController.php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Auth;
use App\Http\API\Slideshare;

class apiController extends Controller
{

    public function index($source)
    {
        $controller=  new $source;
        return $controller->index();
        // if i change code to  $controller=  new Slideshare; it works fine
    }

}

slideshare.php class

<?php

namespace App\Http\API;

class slideshare 
{

    public function index()
    {
         return 'any data'; 

    }

}

laravel error when i use parameter string to create class object

FatalErrorException in apiController.php line 17: Class 'Slideshare' not found

if i change code to

$controller=  new Slideshare; it works fine

Thank you in advance



via Chebli Mohamed

How can I deploy a laravel 5.1 app on google app engine

Can anyone please take me through the process of deploying a laravel 5.1 app on google app engine?



via Chebli Mohamed

getRealPath returning false (Image Intervention and Laravel 5.1)

I'm having a problem while using the getRealPath function.

$file = Input::file('archivo');
$img = Image::make($file->getRealPath());

I get NotReadableException in AbstractDecoder.php line 302. Image Not Readble.

I tried printing the value for $file->getRealPath() with dd() function and it prints false. Also I tried using dd(Input::hasFile( 'archivo' )) and that returned me true.

I can't seem to find an answer, I have tried almost everything I think.

So basically I want to know 2 things.

  1. Why is getRealPath returning me false and not the path?
  2. How am I supposed to send the route to "Image::make()", I keep getting the annoying exception mentioned before even replacing getRealPath(), and sending instead the route as public_path()."routestring".

Thank you!



via Chebli Mohamed

laravel 5 route jquery sortable

I'm using Laravel 5 and use the jquery sortable: http://ift.tt/1eMUFGW

In my sortable.blade.php I have the following script:

  <script>
      $(function() {
          $('#sortMe').sortable({
              update: function(event, ui){
                  var postData = $(this).sortable('serialize');
                      console.log(postData);

                      $.ajax({
                          data: postData,
                               type: 'POST',
                               url: '{{ URL::to('sortable') }}'
                            });
                        }
                    });
                });
  </script>

Further the sortable.blade.php contains the following html

<div id="sortMe">
     <div id="item_1">Test1</div>
     <div id="item_2">Test2</div>
     <div id="item_3">Test3</div>
     <div id="item_4">Test4</div>
     <div id="item_5">Test5</div>
</div>

My route file contains the following:

Route::post('sortable', 'Sortable\SortableController@sortable');

In my SortableController I have at the moment an empty function:

public function sortable() {}

At the moment when I move one item within the div "sortMe", the firebug show me the moved items list : item[]=1&item[]=2&item[]=4&item[]=3&item[]=5 and give me an exception: POST http://localhost/myProject/sortable 500 Internal Server Error 261ms

Any ideas why I get this error? The purpose is that the after moving an item the sortable() function will be called which takes the moved items and save the order of the items within the database. At the moment it seems that there is a problem when calling the sortable() function. Thank you for any help!



via Chebli Mohamed

How can I make a variable that can be accessable throughout my entire application routes/views in Laravel?

I make a cURL request to an API

http://ift.tt/1LXh9TW


I got back this response

    Object
    data: Object
    first_name: "Bob"
    last_name: "Jones"
    message: "Success"
    status: 200

    ___

I grab the first name and last name and concatenate them together and stored into a variable call $name.

$fn = VSE::user('first_name',$username);
$ln = VSE::user('last_name',$username);
$name = ucwords($fn.' '.$ln); // Bob Jones

I want to display this $name on my navigation.

Sending this $name variable with everyview would be a little over kill.

I'm seeking for a better way of doing this.

What should I do to make that variable accessable throughout my application routes/views ?



via Chebli Mohamed

Perform User Authentication if condition is true

I have 2 strings

$password_api = VSE::user('password',$username); //abc
$password     = Input::get('password'); //abc


If they're matched, I want to log the user in

if ( $password == $password_api ) {

    // Not sure what to do in here ... 
    $auth = Auth::attempt();
}


This approach is just for the demo purpose.

How can I do that in Laravel 5 ?

Any hints / suggestion will be much appreciated



via Chebli Mohamed

Sub-domain routing in Laravel on shared hosting

I'm using Laravel framework version 5.1 for my web application that will be run on a shared hosting. Since I have a very limited access to this host, (e.g. I don't have a SSH access, can't create virtual hosts inside the machine etc.) I had to make some tricks to run it smoothly. Here is what I've done so far:

  1. Moved the files inside of the public/ directory to my root directory.
  2. Changed the file paths of auto load registrar in the public/index.php with the new directory.

Everything works as intended except the sub-domain routing. I defined api.myapp.com as wildcard on routes.php but when I try to visit this subdomain, Chrome gives me DNS_PROBE_FINISHED_NXDOMAIN error. Here is the code from routes.php:

Route::group([
    'domain'     => 'api.myapp.com',
    'prefix'     => 'v1',
    'middleware' => 'cors'
], function () {
    // some RESTful resource controllers
});

How can I manage to work this subdomain? What am I missing?

Thanks in advance!



via Chebli Mohamed

Laravel custom validation message parameter

I'm using laravel 5.1. I have a summernotejs form element. I've created a custom validation rule successfully, which takes the HTML provided from the form input, strips the tags, and does a strlen() call on the text content. Therefore I can see the length of a message without any tags in it.

This is my validation rule:

Validator::extend('strip_min', function ($attribute, $value, $parameters, $validator) {
    return strlen(strip_tags($value)) >= $parameters[0];
});

I call the validation rule by specifying: strip_min:10 or strip_min:20 etc, with the number being the minimum string length after stripping tags.

I want to add a custom message, saying that the content lengths needs to be a minimum of n characters long.

The Laravel documentation on this aspect is useless. I've opened my validation.php file, which contains all the error messages.

I've added the key strip_min to the message array, with the message: The :attribute must be at least :min characters.

When I test it, I get the error message:

The notice must be at least :min characters.

How can I convert :min into the number specified in the validation rule?! I've read the documentation but it's all over the place, and I cant understand how to just simply replace :min with the given number.



via Chebli Mohamed

Dynamic type-hinting in Laravel

I was wondering if it is possible to use type-hinting dynamically.

Example:

class Foo {
    __construct(Baz $baz) {
    }
}

class Bar {
    __construct() {
    }

    action() {
        $baz = new Baz;
        return new Foo($baz);
    }
}

class Baz {
    __construct() {
    }
}

I am intending to do it in a generic way so the class will be reusable but in the same time to keep the type hinting:

class Foo {
        __construct(Object $object) {
        }
}



via Chebli Mohamed

Skipping precaching: Cannot read property 'concat' of null`

Here's my question: How might I try to get rid of the 'skipping precaching' and cache everything that comes in from http://ift.tt/1Hdnh4X as the precache list?

Also, is it correct for me to set precache="http://ift.tt/1Hdnh4X" or should I be setting that to a function that grabs the data and returns it instead?

Skipping precaching: Cannot read property 'concat' of null comes out on the console when using My Polymer App

<platinum-sw-cache default-cache-strategy="fastest" cache-config-file="cache-config.json" precache="http://ift.tt/1Hdnh4X">

I am assuming correctly I can precahce a URL like this, right?

I am trying to load a json result from laravel 5.1 to set what my precache should be... I know it's not the most elegant, but I'm new to Polymer, cache, service workers, etc, and using this app as a learning opportunity. It'll be a bit different at the end of the day, but for now I just want to load everything. :)

I want to precache all of the data so that a user can fully utilize this app when offline (though later I'll set it up so that they don't have to precache loads and loads of json requests, only the ones they want, like per book - but that's for later).



via Chebli Mohamed

Caching Lazy Eager Loading Queries in Laravel 5.1

How do I cache the lazy eager loading queries based on the model relationships. For example -

$books = App\Book::all();

$books->load('author', 'publisher');

I can cache the first query with something like this

$books = Cache::remember('allbooks', 60, function() {
             return App\Book::all();
         });

How do I cache the second query?

If there is no direct way, please suggest any workaround, possibly with a sample code.



via Chebli Mohamed

Weird named routes with resource route and parameter - Laravel

I have this route resource:

Route::resource('{module_slug}/post', 'Backend\PostController');

That results in routes like:

cms.{module_slug}.post.index

Should I be bothered by {module_slug} in the name?

I prefer something like cms.module.post.index.

I've found that I can rename them with:

'names' => [
        'index' => 'cms.module.post.index'
]

Is this the way to go? When I used:

'as' => 'module.post'

for the resource I get: module.post.cms.{module_slug}.post.index



via Chebli Mohamed

Posting array of images

I am posting array of images to the controller. There is weird issue which I couldn't understand. The issue is that when I debug the $request variable, it shows me the images array. But, when debug/access that specific array then it doesn't show images array. Following is the screenshot of the debugged variable.

enter image description here

What am I missing?



via Chebli Mohamed

Create menu from self referencing table

I didn't set the model for this table. But i would like to know how to process it in the view. Do I have to create a model for it to maintain it?

how will it looks like

here is the structure of table

Categories
    id 
    parent_category
    title

and the end result would be like this

<ul>
   <li>ACME Products Inc.</li>
   <ul class=”children”>
       <li>Acme Accounting Solutions</li>
       <li>Acme Reseach & Development
   <ul>
   <li>Acme Prototypes Limited</li>
</ul>



via Chebli Mohamed

Laravel 5.1 debugging error page

I am new to this framework. Sometimes it shows me errors in the page, which I have not even change. So how can I localize the exact line where I had made the mistake?

I mean is it possible to activate debugging in Laravel 5.1? and How?



via Chebli Mohamed

Laravel error page

I am new to this framework.Sometimes it shows me errors in the page, which i have not even change. so how can i able to know the exact line where i had made the mistake?

Any help will be greatly appreciated.



via Chebli Mohamed

Laravel 5.1 Sending email shows error

i'm trying to send email in laravel 5.1 but getting following error

Class 'Swift_Transport_EsmtpTransport' not found

My code

public function test_mail() {
  $data = ['name' => 'XXX xxx xxx', 'number' => 1234];
  $sent = Mail::send('emails.fee_pay_success', ['data' => $data], function ($m) use ($data) {
        $m->to('abcd@gmail.com', 'Abcd Efg')->subject('Your Reminder!');
    });
 if( ! $sent) dd("something wrong");
dd("send");
}

My config file mail.php

return [

/*
|--------------------------------------------------------------------------
| Mail Driver
|--------------------------------------------------------------------------
|
| Laravel supports both SMTP and PHP's "mail" function as drivers for the
| sending of e-mail. You may specify which one you're using throughout
| your application here. By default, Laravel is setup for SMTP mail.
|
| Supported: "smtp", "mail", "sendmail", "mailgun", "mandrill", "ses", "log"
|
*/

'driver' => env('MAIL_DRIVER', 'smtp'),

/*
|--------------------------------------------------------------------------
| SMTP Host Address
|--------------------------------------------------------------------------
|
| Here you may provide the host address of the SMTP server used by your
| applications. A default option is provided that is compatible with
| the Mailgun mail service which will provide reliable deliveries.
|
*/

'host' => '',

/*
|--------------------------------------------------------------------------
| SMTP Host Port
|--------------------------------------------------------------------------
|
| This is the SMTP port used by your application to deliver e-mails to
| users of the application. Like the host we have set this value to
| stay compatible with the Mailgun e-mail application by default.
|
*/

// 'port' => env('MAIL_PORT', 587), 'port' =>465,

/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/

'from' => ['address' => 'tucell@onlinefeepayment.in', 'name' => 'DU'],

/*
|--------------------------------------------------------------------------
| E-Mail Encryption Protocol
|--------------------------------------------------------------------------
|
| Here you may specify the encryption protocol that should be used when
| the application send e-mail messages. A sensible default using the
| transport layer security protocol should provide great security.
|
*/

//'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'encryption' => 'ssl',

/*
|--------------------------------------------------------------------------
| SMTP Server Username
|--------------------------------------------------------------------------
|
| If your SMTP server requires a username for authentication, you should
| set it here. This will get used to authenticate with your server on
| connection. You may also set the "password" value below this one.
|
*/

'username' => '',

/*
|--------------------------------------------------------------------------
| SMTP Server Password
|--------------------------------------------------------------------------
|
| Here you may set the password required by your SMTP server to send out
| messages from your application. This will be given to the server on
| connection so that the application will be able to send messages.
|
*/

'password' =>'',

/*
|--------------------------------------------------------------------------
| Sendmail System Path
|--------------------------------------------------------------------------
|
| When using the "sendmail" driver to send e-mails, we will need to know
| the path to where Sendmail lives on this server. A default path has
| been provided here, which will work well on most of your systems.
|
*/

'sendmail' => '/usr/sbin/sendmail -bs',

/*
|--------------------------------------------------------------------------
| Mail "Pretend"
|--------------------------------------------------------------------------
|
| When this option is enabled, e-mail will not actually be sent over the
| web and will instead be written to your application's logs files so
| you may inspect the message. This is great for local development.
|
*/

'pretend' => false,

];



via Chebli Mohamed

mercredi 28 octobre 2015

action helper and routing priority laravel 5

I have two rules

Route::get('this-is-an-awesome-route', 'Ads@getIndex');
Route::controller('ads', 'Ads');

action('Ads@getIndex') renders

http://my-awesome-domain/ads

I want

http://my-awesome-domain/this-is-an-awesome-route

What's the problem ?



via Chebli Mohamed

XMLHttpRequest CROS issues when uploading(post) files to S3 from browser and redirecting to a custom url

This case is easy to understand, and I have paste enough information about the problem. Thank you for your patience. :)

There is a case that I use JQuery File Upload (UI) to upload images to AWS S3 directly from client browser, here is the post data: AWSAccessKeyId: xxxxxx, key: filename.jpg, Policy: xxxxxx, Signature: xxxxx, acl: 'private', success_action_redirect:'http://example.org/test', 'Content-Type': x.type the policy and signature are totally fine, and the image has been uploaded as well.

but there is problem when redirect to the pre-defined url http://example.org/test:

XMLHttpRequest cannot load http://ift.tt/1SayKso. 
The request was redirected to 'http://localhost:8000/test?bucket=mybucket&key=filename.jpg&etag=xxxxxxxx', 
which is disallowed for cross-origin requests that require preflight.

I paste the http request and response for http://ift.tt/1SayKso:

Request:

POST /mybucket/ HTTP/1.1
Host: s3-eu-west-1.amazonaws.com
Connection: keep-alive
Content-Length: 298856
Origin: http://localhost:8000
X-CSRF-TOKEN: H5HRwmtwCVAxIgmAvM8YL5bgayuDyyQV2UKUqnhT
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryhI9Z5605GrykYXvT
Accept: application/json, text/javascript, */*; q=0.01
Content-Disposition: attachment; filename="xxxxxxx"
Referer: http://localhost:8000/xxxxxxxx
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8

Response:

HTTP/1.1 303 See Other
x-amz-id-2: g1VdA6dwEHl+y/C8nSTD7qzxL7gX9o3c0JV7Cj7cKYDeUPNvlrkRzaJEz4PtNFCPZhOAhA8pqzw=
x-amz-request-id: 48C7F5DB54CCEF65
Date: Thu, 29 Oct 2015 02:35:31 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT
Vary: Origin, Access-Control-Request-Headers, Access-Control-Request-Method
ETag: "772d776abbc1bb619d208c92d4b986c9"
Location: http://localhost:8000/test?bucket=mybucket&key=filename.jpg&etag=xxxxxxxx
Content-Length: 0
Server: AmazonS3

And for the redirect endpoint http://example.org/test, which is implemented in Laravel 5.1. Here are the relative routes:

Route::group(['prefix' => 'test'], function () {
    Route::options('/', function(){
        return response(null, 204)
            ->header('Access-Control-Allow-Origin' , '*')
            ->header('Access-Control-Allow-Credentials', 'true')
            ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type')
            ->header('Access-Control-Max-Age', '1728000')
            ->header('Content-Type', 'text/plain charset=UTF-8')
            ->header('Content-Length', '0');
    });
    Route::get('/', function () {
        return response('test', 200)
            ->header('Access-Control-Allow-Origin' , '*')
            ->header('Access-Control-Allow-Credentials', 'true')
            ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type');
    });

});

When GET http://example.org/test directly, here is the HTTP response headers:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type
Access-Control-Allow-Methods:POST, GET, OPTIONS
Access-Control-Allow-Origin:*
Cache-Control:no-cache
Connection:close
Content-Type:text/html; charset=UTF-8
Date:Thu, 29 Oct 2015 02:47:51 GMT
Host:localhost:8000

Any body can help me figure out where is the problem? Thanks!



via Chebli Mohamed

Laravel AuthServiceProvider code explanation

I'm starting to user Gate in Laravel 5.1, and I got this code from some where in the internet.

<?php    

public function boot(GateContract $gate)
{
    $this->registerPolicies($gate);

    /**
     * NOTE!!
     * First time migration will fails, because permissions table doesn't exists.
     */
    foreach($this->getPermissions() as $permission) {
        $gate->define($permission->path, function($user) use ($permission) {

            return $user->hasRole($permission->roles);
        });
    }
}

My question is, what is function($user) use ($permission) { in $gate->define($permission->path, function($user) use ($permission) { ??? Why is there use after function()?

If there're some references, I'd love to know/ read it.



via Chebli Mohamed

How can I install laravel framework for NetBeans 7.4

I have installed Laravel and I want to use use framework annotations and code completion in the NetBeans 7.4 IDE, there is no Laravel plugin in the section "Install plug-ins". I have found a plug in for Netbeans on github but I am unsure how I install it, here is the link http://ift.tt/1MujTKL



via Chebli Mohamed

Laravel 5.1 domPDF not working correctly

hope somebody can help me, I'm trying to generate a report for PDF, so I use barryvdh/laravel-dompdf, maybe the implementetion is wrong, or maybe is just a detail.

The generation works fine, so what I'm trying to do is pass the html as string through a GET AJAX to the controller handling the PDF creator, but when I'm trying to return the PDF is not doing anything. And I'm getting two types of response, one is an error The Response content must be a string or object implementing __toString(), "object" given.

The other thing is that in the debug console returns like garbage.

Here's my controller:

public function generarPDF(Request $request){
        $datos = $request->all();
        $datos = $datos['data'];

        $datos = utf8_encode($datos);

        $data = [];
        $data['html'] = $datos;


        /* Here it return the Error:
        The Response content must be a string or object implementing __toString(), "object" given.*/
        return \PDF::loadView('reportes.pdf', compact('data') );

        /*If I do this it returns nothing, only in the response console throws like garbage...*/
        //return $pdf->download("Hello.pdf");

    }

Thanks...



via Chebli Mohamed

How to make a Laravel 5.1 package in a proper way?

Quite shot Q.

I am writing a short package to communicate with an external Api. Laravel 5.1 doesn't have out of the box methods to send get (http) requests, so i use Guzzle.

I add require { "guzzlehttp/guzzle": "~6.0" } in my package's composer.json

Next step: is to require 'vendor/autoload.php'; Where should i put this in my package?

Whithout that i still get an error:

FatalErrorException in RestClient.php line 31:

Class 'GuzzleHttp\Client' not found

Much appreciate your advice



via Chebli Mohamed

laravel babel not babeling ...

Consider the following:

var RecentSignups = require('./company_admin/dashboard/recent_signups');
var CapitalRaised = require('./company_admin/dashboard/capital_raised');
var InvestmentTransactions = require('./company_admin/dashboard/investment_transactions');
var InvestorsCurrentlySignedIn = require('./company_admin/dashboard/investors_signed_in_today');
var InvestorsSignedUp = require('./company_admin/dashboard/investors_signed_up');
var CompanyEvents = require('./company_admin/dashboard/company_events');
var RecentInvestments = require('./company_admin/dashboard/recent_investments');
var InvestorsTable = require('./company_admin/dashboard/investors_table');

Now consider the following elixir command for gulp:

elixir(function(mix) {
  mix.sass(bootstrapPaths, 'public/css/bootstrap.css')
       .sass('admin.scss', 'public/css/admin.css')
       .babel([
         '/react/react_app.js',
       ])
       .sass([
           'company_admin/company_admin.scss',
       ], 'public/css/company_admin.css')
       .phpUnit();
});

No errors are spit out, how ever:

'use strict';

var RecentSignups = require('./company_admin/dashboard/recent_signups');
var CapitalRaised = require('./company_admin/dashboard/capital_raised');
var InvestmentTransactions = require('./company_admin/dashboard/investment_transactions');
var InvestorsCurrentlySignedIn = require('./company_admin/dashboard/investors_signed_in_today');
var InvestorsSignedUp = require('./company_admin/dashboard/investors_signed_up');
var CompanyEvents = require('./company_admin/dashboard/company_events');
var RecentInvestments = require('./company_admin/dashboard/recent_investments');
var InvestorsTable = require('./company_admin/dashboard/investors_table');
//# sourceMappingURL=all.js.map

This is not right. Why didn't it essentially "require"? I am using laravel 5.1 and elixir 3.4.x



via Chebli Mohamed

Howto Test delete method in Laravel 5.1

I have a method in controller that I would like to test

public function destroy(Instrument $instrument)
{
    $instrument->delete();

    flash()->success('Instrument Deleted Successfully!');

    return Redirect::route('instrument.index');
}

If I am to test controller manually method works fine.

However, I have been trying to test this without much luck... btw, this method is accessed via DELETE method.

Below are some example of calls that I have tried:

$this->action('DELETE', 'InstrumentController@destroy', ['id' => 19]);

And this..

$this->delete('/instrument/destroy/19');

I was trying to test using $this->visit() but when you click on delete button a bootstrap toolkit appears, because its not preloaded in the dom i am unable to test using $this->visit()...

If some one could help out, would be great



via Chebli Mohamed

laravel route with parameter not coming from url

I have multiple routes that look like this:

Route::get('pending-submit', 'CasesController@cases');
Route::get('submited', 'CasesController@cases');
Route::get('closed', 'CasesController@cases');

I have been looking around even in the router API documentation and I can't find a solution for my requirement other than creating multiple methods within the controller. The method does the exact same query except for adding a where clause to identify the different status between each case, what I was trying to do is have a method like this

public function cases($whereStatus = 0){
    return Cases::where('status', $whereStatus)->get();
}

Instead of doing this:

public function pendingCases(){
    return Cases::where('status', 0)->get();
}

public function submitedCases(){
    return Cases::where('status', 1)->get();
}

public function closedCases(){
    return Cases::where('status', 2)->get();
}

But I can figure a way to pass that parameter to the method from the route so I now have to create a method for each route which does not seem necessary to me. I understand I could just generate urls with the get parameter in it but I wanted to make that cleaner, is there a way for me to add that parameter without having it in the url?



via Chebli Mohamed