vendredi 30 septembre 2016

Do i need to change database configuration in database.php file in laravel when upload to server?

Do i need to change database configuration in database.php file in laravel when upload to server?

 'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
        'strict' => false,
        'engine' => null,
    ],



via Chebli Mohamed

ReflectionException in Container.php line 741: Class App\Http\Controllers\Backend/ItemsController does not exist

i constantly get this error after i created the update/edit function, route and layout. After some research i tried:

namespace App\Http\Controllers\Backend\ItemsController; 

but still nothing.

Controller:

<?php

namespace App\Http\Controllers\Backend;

use Illuminate\Http\Request;
use App\Models\Item;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Laracasts\Flash\Flash;



class ItemsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        $items = Item::orderBy('id', 'ASC')->paginate(5);

        return view('backend.item.list')->with("items", $items);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('backend.item.form');
    }


    public function store(Request $request)
    {
        // mejora:
        // $item = new Item($request->all());
        $item = new Item;
        $item->name = $request->get('name');
        $item->pompadour = $request->get('pompadour');
        $item->description = $request->get('description');
        $item->outstanding_image = '';
        $item->save();

        Flash::success("Se ha agregado un nuevo item " . $item->name . " con exito");

        return redirect()->route('item.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $item = Item::find($id);

        //return view('items.show')->withItem->($item);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
         $item = Item::find($id);
         return view('items.edit')->with('item', $item);
    }

    public function destroy($id)
    {
        // delete
        $item = Item::find($id);
        $item->delete();

        Flash::error("El item " . $item->name . " ha sido eliminado correctamente");

        return redirect()->route('item.index');
    }

    public function update(Request $request, $id)
    {
        $item = Item::find($id);
        $item->name = $request->name;
        $item->pompadour = $request->pompadour;
        $item->description = $request->description;
        $item->save();

        Flash::info("El item " . $item->name . " ha sido editado correctamente");

        return redirect()->route('item.index');

    }
}

Routes ( this are the only one that do not work, i also have the destroy route, store and create):

Route::get('item/{id}/edit', ['as' => 'items.edit', 'uses' => 'Backend/ItemsController@edit']);
Route::put('item/{id}', ['as' => 'items.update', 'uses' => 'Backend/ItemsController@update']);

While my form action look like:

<form action="" method="PUT" class="form-horizontal">

Thanks for taking the time reviewing my code.



via Chebli Mohamed

Yajra datatable search returns no data

I rendered a server side datatable using Yajra in Laravel 5.1. But when i am trying to search any record, using the search box, I get the following message, No matching records found. I tried adding searchable: true in all the columns but still the problem is same.

Please help me with this issue.

My code:

JS:

$(function () {
        var table = $('#people-table').DataTable({
            "order": [[ 0, "asc" ]],
            pageLength : 50,
            lengthMenu : [50,100,150],
            "scrollX": false,
            "processing": true,
            "serverSide": true,
            "ajax": {
                url: "/people-view",
                data: {'_token': "{!! csrf_token() !!}",'company_name':""},
                method: "post"
            },
            columns: [
                {data: getFNameLName, name: 'first_name'},
                {data: 'data.title', name: 'title'},
                {data: 'data.country', name: 'country'}
            ]
        });
    });
    function getFNameLName(data, type, dataToSet) {
        return data.data.first_name + " " + data.data.last_name;
    }

HTML

<table class="display table table-stripped" id="people-table" cellspacing="0"
                                   style="table-layout: auto;">
                                <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Job Title</th>
                                    <th>Country</th>
                                </tr>
                                </thead>
                            </table>

Routes:

Route::post('people-view','UserController@peoplesDetails');

Controller:

public function peoplesDetails(Request $request)
    {
        $company_name = $request->input('company_name');
        $people_detail = \App\People::where('data.current_companies.company', '=', $company_name)->
                        select('data.first_name', 'data.last_name', 'data.title', 'data.country')
                            ->take(150)->get();
        return Datatables::of($people_detail)
        ->addColumn('name',function ($people_detail){
            return $people_detail->first_name . " " . $people_detail->last_name;
        })
            ->addColumn('title',function ($people_detail){
                return $people_detail->title;
            })
            ->addColumn('country',function ($people_detail){
                return $people_detail->country;
            })->make(true);
    }



via Chebli Mohamed

jeudi 29 septembre 2016

laravel 5.2 session not persist on route change

laravel 5.2 session not persist after route change,

I have not used any middleware. session returns all values in controller when i put session but it forgets when redirect to another route.

here is my routes

Route::auth();

Route::get('login','LoginController@login');

Route::post('login','LoginController@check');

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

Route::post('school/store','HomeController@store');



via Chebli Mohamed

How to implement licensing feature in web app using laravel 5.1+

I am working on laravel 5.1+ project which is divide in two part one is a centralized database management and another part will be for clients to manage their services. Centralized database application have the feature to manage client application. The centralized database application will have a list of clients with services offered and the validity of the services.

To manage the above process there should be licensing process and each client has to purchase the license and license must have the validity. There should be a manual and automatic validation of license.

If license expire then client can use only the basic feature of the application not more than that and if license will expire will a define period then a message should popup on client application.

Please friends, help me to implement this feature, is there any plugin available. If yes where to start or example to start on. If i need to do from scratch then let me know the flow.



via Chebli Mohamed

Laravel complex query

I'm re-working an already coded "crafting" system that has is based off a set of database "recipes" which has up to five items and quantities (ex: item1 and item1qty). Now previously it was important to order the items in the recipe in the right order, which made validation easy as it was just looking at what the user put as item1 and item1qty etc and matching them straight across.

We'd like to now have it accept ingredients in any order. I know this can be done with query functions, but I fear I'm off base as the solution I came up with marks it as a valid recipe if the user has even part of a recipe (say a recipe contains 3 ingredients, if they enter only one of those ingredients it will validate even without the other 2 proper ingredients and amounts). My solution is also quite long, is there a way to streamline it a bit?

$recipe = DataRecipe::where(function ($query) use($request) {
        $query->where(function ($q) use($request) {
            $q->where(function($q2) use ($request) {
                $q2->where('item1', $request->item1)->where('item1qty', $request->item1qty);
            })->orWhere(function($q2) use ($request) {
                $q2->where('item2', $request->item1)->where('item2qty', $request->item1qty);
            })->orWhere(function($q2) use ($request) {
                $q2->where('item3', $request->item1)->where('item3qty', $request->item1qty);
            })->orWhere(function($q2) use ($request) {
                $q2->where('item4', $request->item1)->where('item4qty', $request->item1qty);
            })->orWhere(function($q2) use ($request) {
                $q2->where('item5', $request->item1)->where('item5qty', $request->item1qty);
            });
        })->where(function ($q) use($request) {
            $q->where(function($q2) use ($request) {
                $q2->where('item1', $request->item2)->where('item1qty', $request->item2qty);
            })->orWhere(function($q2) use ($request) {
                $q2->where('item2', $request->item2)->where('item2qty', $request->item2qty);
            })->orWhere(function($q2) use ($request) {
                $q2->where('item3', $request->item2)->where('item3qty', $request->item2qty);
            })->orWhere(function($q2) use ($request) {
                $q2->where('item4', $request->item2)->where('item4qty', $request->item2qty);
            })->orWhere(function($q2) use ($request) {
                $q2->where('item5', $request->item2)->where('item5qty', $request->item2qty);
            });
        })->where(function ($q) use($request) {
            $q->where(function($q2) use ($request) {
                $q2->where('item1', $request->item3)->where('item1qty', $request->item3qty);
            })->orWhere(function($q2) use ($request) {
                $q2->where('item2', $request->item3)->where('item2qty', $request->item3qty);
            })->orWhere(function($q2) use ($request) {
                $q2->where('item3', $request->item3)->where('item3qty', $request->item3qty);
            })->orWhere(function($q2) use ($request) {
                $q2->where('item4', $request->item3)->where('item4qty', $request->item3qty);
            })->orWhere(function($q2) use ($request) {
                $q2->where('item5', $request->item3)->where('item5qty', $request->item3qty);
            });
        })->where(function ($q) use($request) {
            $q->where(function($q2) use ($request) {
                $q2->where('item1', $request->item4)->where('item1qty', $request->item4qty);
            })->orWhere(function($q2) use ($request) {
                $q2->where('item2', $request->item4)->where('item2qty', $request->item4qty);
            })->orWhere(function($q2) use ($request) {
                $q2->where('item3', $request->item4)->where('item3qty', $request->item4qty);
            })->orWhere(function($q2) use ($request) {
                $q2->where('item4', $request->item4)->where('item4qty', $request->item4qty);
            })->orWhere(function($q2) use ($request) {
                $q2->where('item5', $request->item4)->where('item5qty', $request->item4qty);
            });
        })->where(function ($q) use($request) {
            $q->where(function($q2) use ($request) {
                $q2->where('item1', $request->item5)->where('item1qty', $request->item5qty);
            })->orWhere(function($q2) use ($request) {
                $q2->where('item2', $request->item5)->where('item2qty', $request->item5qty);
            })->orWhere(function($q2) use ($request) {
                $q2->where('item3', $request->item5)->where('item3qty', $request->item5qty);
            })->orWhere(function($q2) use ($request) {
                $q2->where('item4', $request->item5)->where('item4qty', $request->item5qty);
            })->orWhere(function($q2) use ($request) {
                $q2->where('item5', $request->item5)->where('item5qty', $request->item5qty);
            });
        });
    })->where('tool', $request->tool)->first();



via Chebli Mohamed

Database [] not configured Laravel 5

I create new db in phpmyadmin and new tables.

Then i do

    public function next(Request $request){
    $langs = DB::connection('mydb')->select('select * from lang');
    }

and get

Database [compgen] not configured.

in my .env

DB_HOST=localhost
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=123

in my config/database.php

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



via Chebli Mohamed

how to use multiple session driver in laravel

In Laravle5.3 I want to use multiple session driver,in the frontend I just use redis as the driver but in the backend have to use database as the driver,I tried but cant find a way to solve this problem,first I just use middleware before the session start,but you know if change the drive,the other data will disappear,it did`t work,how can i configure this,thanks a lot.



via Chebli Mohamed

mercredi 28 septembre 2016

Enable features of Laravel project to update and delete json objects with firebase

I am using firebase and mysql as the backend. I can insert data to firebase using laravel project. But deleting and updating operations only valid for mysql. I want to make active those features for firebase also. I am using 'Mpociot\Firebase\SyncsWithFirebase' to sync data with firebase. It is perfectly working for insertion only. But there's already built in methods for all the database operations in the syncsWithFirebase php file. I need a solution for that guys.

 public function store(Requests\EventRequest $request){

    $request->all();

    $current=Carbon::now();
    $t=substr($current,11,-3);
    $d=substr($current,0,-9);
    $st=explode(":",$t);
    $currentTime=$st[0].$st[1];
    $postTime=$_POST['time'];
    $time=explode(":",$postTime);

    $insertTime=$time[0].$time[1];
    $date=$_POST['eventDate'];
    if(strcmp($d,$date)==0) {
       if ($currentTime > $insertTime) {


           Session::flash('errorTime', 'Time is passed.');
           return redirect()->back()->withInput();
       }
    }
    $events=EventCal::all();
    foreach($events as $ev){
        $ti=substr($ev->time,-8,5);

        if( (strcmp($ev->eventDate,$date)==0) && (strcmp($ev->venue,$_POST['venue'])==0) && (strcmp($ti,$postTime)==0) ){

            Session::flash('errorDate', 'There is already an event for this time,Venue and Starting Date');
            return redirect()->back()->withInput();
        }
    }



    $input=Request::all();

    if (Input::hasFile('photo')) {
        $file = Input::file('photo');
        // getting image extension
        $extension = $file->getClientOriginalExtension();
        // renameing image
        $fileName = rand(11111, 99999) . '.' . $extension;
        // uploading file to given path
        $file->move('images', $fileName);
        $input['photo'] = "images/$fileName";
    }


    EventCal::create($input);
    flash()->success('Successfully Added','Good Job');
    return redirect('/evntform');

}

Above is the code for inserting which works fine.

 public function index5($id){

    $evnt = EventCal::where('id', '=', $id)->delete();
    return redirect('/dcalendar');
}

And above code is to deleting which is not sync with firebase.

Below is the model class code.

<?php namespace App;

  use Illuminate\Database\Eloquent\Model;
  use Mpociot\Firebase\SyncsWithFirebase;
  class EventCal extends Model{
   use SyncsWithFirebase;
   protected $fillable = [
    'title',
    'venue',
    'time',
    'eventDate',
    'type',
    'photo',
    'color',
    'endDate'
];
}

I tried to find the answer for several time and even asking from my friends on stack. So if anyone can find a solution to my problem it will be a great worthy to me.



via Chebli Mohamed

mardi 27 septembre 2016

Submit a form using Ajax

First, here is my code :

routes.php

$router->resource('vips','formController');

formController.php (im only posting the concerned function)

public function store(CreateVipRequest $request, Vip $vip, Pool $pool, Url $url)
{
    $new_vip = $vip->create($request->except(['srv_hostname', 'srv_ip', 'srv_port','url']));
    $pool->fill($request->only(['srv_hostname', 'srv_ip', 'srv_port']));
    $url->fill($request->only(['url']));

     /* Some more inserts on the database...*/

    return redirect()->route('vips.show', [DB::table('vips')->max('id')]);
}

My code submits the form, and after some json requests to a distant Api (and some databases insertions) it redirects to the show view.

Now I want to add a second button that submits the form via Ajax.

Question : Is there a way to use the same function store ? I need it to be able to process both an ajax submit and a normal submit.



via Chebli Mohamed

lundi 26 septembre 2016

Laravel shows parameter name instead of value (when using optional parameter in route)

I've got a form where a user can enter a start location, when submitting he will go to a map centered on this location. He can also just skip this step and go to the map directly. (this is the simplified version to skip the whole background story)

This is the first piece of code, when the user has used the form it will take the start location from the form and redirect to the map: (never mind the planning variable, it will always be 'own' for the purpose of this case)

Route::post('InitiateUserTrip', ['as' => 'InitiateUserTrip', function(WelcomeFormRequest $request) 
{
    if (Input::get('planning') == 'own') {
        return Redirect::route('Map',array('startLocation', Input::get('startLocation')));
    } else {
      return view('welcome');
    }
} ]);

This is the map route, the startLocation is optional as explained above. (API key would be my personal API KEY.) What I see happening here is that the debugbar is showing 'startLocation' instead of the value of the parameter. (name instead of value)

Route::get('Map/{startLocation?}', ['as' => 'Map', function($startLocation = null)
{
    $map = new Map('API KEY',$startLocation,'GMainMap');    
    $googleMap = $map->getMap();
    $node = new Node();
    $node->loadBySelection('ALL');
    $nodes = $node->getNodes();
    \Debugbar::info("Map: " . $startLocation);
    return View::make('map')->with('map', $googleMap)
                            ->with('nodes',$nodes)
                            ->with('startLocation',$startLocation);
}]);

I started playing with the URL to see what was going on. Assuming the user entered 'Miami' as startLocation this would result in following URL:

http://ift.tt/2d3emOm => Debugbar would show 'startLocation'

When I modify the URL myself to http://ift.tt/2dtoKwW => Debugbar would show 'Miami'

It's not just Debugbar that would show wrong contents. I try to geocode based on this variable and it fails because it sees the contents as 'startLocation' as well.

I may be able to solve this problem by creating two routes, one with and one without parameter but I suppose I'm just missing something obvious.



via Chebli Mohamed

dimanche 25 septembre 2016

Laravel 5.2 Vue.js computed doesn't work

How can I show objects returned by vue? The provinces are Ok, But cities v-for doesn't work.

This is My Blade :

<select v-model="ProvinceModel" name="province" id="province" class="border-radius-0 form-control padding-y-0">
    <option v-for="province in provinces" value="@"> @ </option>
</select>

<select name="city" id="city" class="border-radius-0 form-control padding-y-0">
    <option v-for="city in cities" value="@"> @ </option>
</select>

This is my scripts

new Vue({
        el: '#vue',
        methods: {
            fetchProvinces: function () {
                this.$http.get('').then(function (provinces) {
                    this.$set('provinces', provinces.data)
                });
            }

        },
        computed: {
            cities() {
                this.$http.get("/" + this.ProvinceModel).then(function (cities) {
                    console.log(cities.data);
                    this.$set('cities', cities.data)
                });

            }
        },
        ready: function () {
            this.fetchProvinces()
        },
    });

And route

Route::get('cities/{provinces_id}', function ($id = 8) {
    return \App\province::find($id)->cities()->get();
})->where('id', '[0-9]+');



via Chebli Mohamed

vendredi 23 septembre 2016

Rename column on Laravel 5.1 migration [SQL SERVER][Linux]

I'm writting a migration on Laravel 5.1 and after created a table I rename the table name and the columns, It works running the migration for a MySQL database but on SQL Server 2008 fails trying to rename the columns and outputs the next error:

Next Doctrine\DBAL\DBALException: An exception occurred while executing 'SELECT    col.name,
                     type.name AS type,
                     col.max_length AS length,
                     ~col.is_nullable AS notnull,
                     def.definition AS [default],
                     col.scale,
                     col.precision,
                     col.is_identity AS autoincrement,
                     col.collation_name AS collation,
                     CAST(prop.value AS NVARCHAR(MAX)) AS comment -- CAST avoids driver error for sql_variant type
           FROM      sys.columns AS col
           JOIN      sys.types AS type
           ON        col.user_type_id = type.user_type_id
           JOIN      sys.objects AS obj
           ON        col.object_id = obj.object_id
           JOIN      sys.schemas AS scm
           ON        obj.schema_id = scm.schema_id
           LEFT JOIN sys.default_constraints def
           ON        col.default_object_id = def.object_id
           AND       col.object_id = def.parent_object_id
           LEFT JOIN sys.extended_properties AS prop
           ON        obj.object_id = prop.major_id
           AND       col.column_id = prop.minor_id
           AND       prop.name = 'MS_Description'
           WHERE     obj.type = 'U'
           AND       (obj.name = 'roles' AND scm.name = SCHEMA_NAME())':

I need that the migration working on both databases. My migration code is:

public function up()
{
  Schema::create('cat_tipo_usuario', function (Blueprint $table) {
      $table->increments('id_tipo_usuario');
      $table->string('txt_tipo_usuario');
      $table->timestamps();
  });
  //Se renombra la tabla
  Schema::rename('cat_tipo_usuario','roles');
  //Se cambia el nombre de las columnas
  Schema::table('roles',function($tabla){
    $tabla->renameColumn('id_tipo_usuario','id');
    $tabla->renameColumn('txt_tipo_usuario','nombre');
  });
}

If I comment the lines where I rename the columns the migration runs correctly, so the driver and the connection are working well.



via Chebli Mohamed

Laravel: sending parameter id type int returns null, String works fine

I am facing a strange behaviour of Laravel when I am sending request with parameter of id. If I user integer as type of the parameter the request returns null. If the parameter type is String, it returns result as expected. How can this behavour be explained? Should I always use String typed parameters? Here is my code:

    $client_id =  $request->get('client_id');
    $client = Auth::user()->**clients**->where('id', $client_id);

    if($client->isEmpty()) {
        return response(['not your client', 433]);
    }

this is how clients look:

$this->belongsToMany('App\User', 'waiter_client', 'waiter_id', 'client_id');

Thank you.



via Chebli Mohamed

jeudi 22 septembre 2016

Upgrade from 5.0 to 5.1 vendor trait not load

I upgrade my Laravel 5.0 to 5.1 I notice that my TrustyTrait is not loaded in 5.1 I need to use the method "is",

Here is the debug output from 5.0, I simply change the method from "is" to "asd" to display the error. As you can see, it actually called TrustyTrait.php line 155

in Builder.php line 1999
at Builder->__call('asd', array('administrator'))
at Builder->asd('administrator')
at call_user_func_array(array(object(Builder), 'asd'), array('administrator')) in Builder.php line 933
at Builder->__call('asd', array('administrator'))
at Builder->asd('administrator')
at call_user_func_array(array(object(Builder), 'asd'), array('administrator')) in TrustyTrait.php line 155
at User->__call('asd', array('administrator')) in AdminController.php line 19
at User->asd('administrator') in AdminController.php line 19

Here is the debug output from 5.1, the correct method from "is" but it display the error. After Builder.php then it go to Model.php, but for 5.0, it go to TrustyTrait.php

in Builder.php line 2093
at Builder->__call('is', array('administrator'))
at Builder->is('administrator')
at call_user_func_array(array(object(Builder), 'is'), array('administrator')) in Builder.php line 1015
at Builder->__call('is', array('administrator'))
at Builder->is('administrator')
at call_user_func_array(array(object(Builder), 'is'), array('administrator')) in Model.php line 3444
at Model->__call('is', array('administrator')) in AdminController.php line 19
at User->is('administrator') in AdminController.php line 19

What is the thing I missed out?

Here is the code for AdminController:

public function isAdmin(){
        //Check Member Auth
        $this->beforeFilter('@filterRequests');
    }

    public function filterRequests()
    {

        if (!is_object(\Auth::user()) || !\Auth::user()->is('administrator')) return \Redirect::guest('/admin/login')->with('error','You are not Unauthorized');
    }



via Chebli Mohamed

Configure Laravel project to update and delete json objects

I am using firebase and mysql as the backend. I can insert data to firebase using laravel project. But deleting and updating operations only valid for mysql. I want to make active those features for firebase also. I am using 'Mpociot\Firebase\SyncsWithFirebase' to sync data with firebase. It is perfectly working for insertion only. I need a solution for that guys.



via Chebli Mohamed

How to add custom header and footer in laravel tcpdf?

How can I add custom header and footer text in tcpdf using laravel controller

Following the TCPDF doc I can create a pdf file fine. but when I want to add custom footer text I didn't do that.

How can I add custom footer in tcpdf or you have any solution for the custom footer any other package which I will use custom footer easily please suggest me.



via Chebli Mohamed

laravel : how to run class auto

I have an api class and i want that when the user logged in system this class should run auto and return true or false. i don't want to call this to every class.

i don't want this :

$api = new Api();

what can i do for this or it could be that :

$ret = Api::run(); // this will run auto when the user logged in but run only one time not run every redirect or refresh

and i want use it like this:

return View('api.show')->withApi($ret);

Should this return a bool variable and use every class which i want to use it in?



via Chebli Mohamed

Array validation for table inputs in laravel 5.1

I am trying to give a validation for array inputs using table ,if the inputs are empty it should suppose to give a validation for each input box border as red color. My table code is like we can add multiple no of rows by click add button like My table view

My validations are coming like as in the below image shown My current validation output

and i want validation something like as below using $errors and has-feedback in bootstrap laravel My desired output

table view code:

<form action="" method="post"  enctype="multipart/form-data">
              <input type="hidden" name="_token" value="}" />
              <table class="table table-bordered table-striped-col nomargin" id="table-data">
                <tr align="center">
                  <td>Event Name</td>
                  <td>Event Code</td>
                  <td>Event Date</td>
                  <td>City</td>
                  <td>Country</td>
                </tr>
                <tr>

                    @if(null != old('eventname')) 
       @for($i=0;$i<count(old('eventname'));$i++)

          <td>
             <div class="form-group has-feedback " id="">
                <input type="text" class="form-control " autocomplete="off" name="eventname[]" value="">
                @if ($errors->has('eventname'.$i)) 
                    <p class="help-block"><span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
                    </p>
                @endif
            </div>
         </td>
      @endfor
  @else 
      <td>
        <div class="form-group has-feedback " id="">
            <input type="text" class="form-control " autocomplete="off" name="eventname[]" >
        @if ($errors->has('eventname')) 
           <p class="help-block"><span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
      </p>
        @endif
       </div>
      </td>
 @endif

                  <td>
                    <input type="text" class="form-control" autocomplete="off" name="eventcode[]" >
                  </td>
                  <td>
                    <input type="text" class="form-control dob"  autocomplete="off" name="date[]" >
                  </td>
                  <td>
                    <input type="text" class="form-control" autocomplete="off" name="city[]" >
                  </td>
                  <td>
                    <input type="text" class="form-control" autocomplete="off" name="country[]" >
                  </td>
                  <td>
                    <input type="button" value="+" class="add btn btn-success">
                    <input type="button" value="-" class="delete btn btn-danger">
                  </td>
                </tr>
              </table>
              </br>
              <center> <button type="submit" class="btn btn-primary" name="submit">Submit</button></center>
            </form>

my controller is like below:

public function postEvent( EventRequest $request ) {

            $data = Input::get();

            for($i = 0; $i < count($data['eventname']); $i++) {
                $c= new Event();

                $c->event = $data['eventname'][$i];
                $c->eventcode = $data['eventcode'][$i];
                $c->date = $data['date'][$i];
                $c->city = $data['city'][$i];
                $c->country  = $data['country'][$i];
                $c->save();

             }

              $request->session()->flash('alert-success', 'Event was successful added!');
              return redirect('executor/all');


}

and then my validation code in EventRequest.php

public function rules()
{



     foreach($this->request->get('eventname') as $key => $val)
                  {
                    $rules['eventname.'.$key] = 'required';
                  }


    return $rules;


}

I am using has-feedback error code inside my table for the first input .But still the validations are coming in the same way i could not able to find what was the mistake in my code.

Any help would be appreciated. Thank you



via Chebli Mohamed

mercredi 21 septembre 2016

laravel session management in subdomain

I am struggling to manage session between domain and sub-domain my domain is example.com having own laravel(5.1) folder structure and other sub-domain having its own laravel(5.1) folder structure

domain and sub-domain access same database

below domain look like

example.com
forum.example.com
access same database "mydatabase"

session management occured only on example.com have numbers of user. I would like to access users same session in forum.example.com



via Chebli Mohamed

Laravel 5.1 not using correct .env values

I'm using Laravel 5.1.44, and even though I have both a .env.testing file setup with different values, as well as App::environment() returning 'testing', Laravel still seems to only be using values from the main .env file.

Is there something else I should be double-checking to make sure I didn't screw up or forget to set something?



via Chebli Mohamed

Issue running phpunit tests on laravel5.1

I Am trying to test api with laravel 5.1 and phpunit for a login module which is divided into 2 parts

  • Check email address
  • get password and authenticate

Now in the first part an api is called which sends the response.error as false for which the follow is the test case code written.

class LoginPageTest extends TestCase
{
use WithoutMiddleware;
/**
 * A basic test example.
 *
 * @return void
 */
public function testExample()
{

$response = $this->call('POST', '/check-user', ['email' => 'john@gmail.com']);

    $this->assertEquals(200, $response->status());

    }
}

But on running the test form the terminal(vendor/bin/phpunit), I get the following error.

Time: 947 ms, Memory: 14.75MB

There was 1 failure:

1) LoginPageTest::testExample
Failed asserting that 500 matches expected 200.

project/tests/LoginPageTest.php:32

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

When i test thru postman i get the desired result in the json format. Is it something to do with my code or phpunit?



via Chebli Mohamed

Testing in Laravel without passing through auth

I'm trying create a test in Laravel 5.1 but I want to use it without the authorization form.

In my RoleController class I put this in order to :

public function __construct()
{
    $this->middleware('auth');
}

I've tried using use WithoutMiddleWare; but did'nt work. This is the phpunit output:

A request to [http://localhost/nuevo/rol] failed. Received status code [500].

Also tried using $this->withoutMiddleware(); for each test method but that din't work either. This is the phpunit output:

InvalidArgumentException: Nothing matched the filter [nombre] CSS query provided for [http://localhost/auth/login].

Instead of visit the "nuevo/rol" route the test make a request to "auth/login" as it works using the auth form.

Is there a method to test without using the authorization form or I need to put in my test code the logic to use it?



via Chebli Mohamed

Can we use firebase to all the data manipulation processes?

I already known how to write data to database in firebase. But I couldn't delete from it. App\EventCal::where('id', 7)->delete();

I have tried above query by running after php artisan tinker command. So can anyone help me?



via Chebli Mohamed

Laravel 5.1 kernel running correctly, but scheduler not

My software is hosted on a dedicated server and has been running great for the past 2 months since I launched it. Today I woke up and realized the kernel never ran the console commands. The cron job command set on my server is:

php myApp/artisan schedule:run >> /dev/null 2>&1

I have tested a few things and realized the cron job is executing the schedule() function in app/Console/Kernel.php, however, it is not running any of the scheduled commands. Furthermore, within the schedule() function, I did:

protected function schedule(Schedule $schedule) 
{
   // send an email to myself saying "SCHEDULER STARTED"

   $schedule->call(function () {
      // send an email to myself saying "IN CALL FUNCTION"
   })->everyMinute();
}

I get the emails saying "SCHEDULER STARTED" every 1 minute, but I do not get any emails saying "IN CALL FUNCTION". I do not believe I have changed anything that would effect this. I also think it's worth mentioning that when I SSH into the server and run "php artisan some-console-command", it will run "some-console-command" successfully. If you need me to give any more info please let me know.

Unrelated, but as a temporary fix to run my console commands, for each console command I have put the code from the commands handle() function into the Kernels schedule() function (now my code is sloppy and I can't stand unorganized code D:).



via Chebli Mohamed

laravel elixir mapping similar file

I have many different files which I combined in one file via elixir and gulp. I also minimize some files which has similar name and different source and also this files storing in the different folders. But in generated .map-file I got only unique names of files. And when I debugging my js I got wrong file. I don't want rename this files or separate theirs in the different built files. Can I create alias for the similar named files?



via Chebli Mohamed

How to properly load files through Laravel queue, payload is truncated due to many records?

Is there a way to load files on disk when the Job executes. I noticed the Laravel queue puts the data as a json on the payload column of my jobs table on the database. I am using the database driver for queues. Is there proper way to do this?



via Chebli Mohamed

Jquery not load form rendered from foreach cicle

I'm tring to render a form of details foreach item in a cart, on Laravel 5.2. By Clicking on checkbox ("#couponyes" or "#couponno") the page need to render or a data taken from database included in div whit id="azienda" (if #couponyes is hit) or a input form (if #couponno is hit) with div id="ritiro". Here is the full code:

<?php 
                     $carrelli = DB::table('carrello')->where('carrello.entry_by', \Session::get('uid'))->join('tariffe', 'tariffe.id', '=', 'carrello.id_tariffa' )->join('servizi', 'tariffe.id_servizio', '=', 'servizi.id')->distinct()->select('servizi.nome as nome_servizio', 'servizi.mod_servizio as mod_servizio', 'tariffe.geo as geo', 'carrello.source_geo as source', 'carrello.destination_geo as destination' )->get(); 

                    ?>
                  @foreach($carrelli as $carr)
                    @if(empty($carr->geo))
                    <fieldset style="height:600px">
                        <legend></legend>
                        <div class="row">
                            <div class="col-lg-6">
                              @if(!empty($coupon))
                                <p>Confermi di voler utilizzare gli indirizzi di presa e consegna previsti dalla tua la convenzione aziendale  ?</p>
                                 <label class="radio-inline">
                                    <input id="couponyes" type="radio" required name="coupon">&nbsp;&nbsp;   Si
                                  </label>
                                  <label class="radio-inline">
                                    <input id="couponno" type="radio" name="coupon">&nbsp;&nbsp;         No
                                  </label>
                                <div id="azienda" style="display:none;">
                                  <?php $punti_ritiro = DB::table('punti_ritiro_aziende')
                                    ->where('entry_by', $azienda->Id)
                                    ->where('id_tipologia', 1)
                                    ->orWhere('id_tipologia', 3)
                                    ->where('attivo', 1)
                                    ->get();
                                    $punti_consegna = DB::table('punti_ritiro_aziende')
                                    ->where('entry_by', $azienda->Id)
                                    ->where('id_tipologia', 2)
                                    ->orWhere('id_tipologia', 3)
                                    ->where('attivo', 1)
                                    ->get();
                                    ?>
                                  <div class="form-group" style="margin-top:50px">
                                    <label for="state">Punto di ritiro</label>
                                        @foreach($punti_ritiro as $punto_ritiro)
                                        <input type="text" readonly value=""></option>
                                        @endforeach
                                  </div>
                                  <hr>
                                  <div class="form-group" style="margin-top:50px">
                                    <label for="state">Punto di consegna</label>
                                        @foreach($punti_consegna as $punto_consegna)
                                        <input type="text" readonly value=""></option>
                                        @endforeach
                                  </div>
                                    <div>

                                    
                                    </div>
                                </div>
                                <div id="ritiro" style="display:none; margin-top:20px; margin-bottom:20px" >
                                @if($carr->mod_servizio == 1)    
                                  <div class="form-group">
                                    <label for="state">Punto di ritiro</label>  
                                    <input type="text" required name="indirizzo_ritiro" id="source1" class="form-control">
                                  </div>
                                @elseif($carr->mod_servizio == 2)
                                  <div class="form-group">
                                    <label for="state">Punto di consegna</label>  
                                    <input type="text" required name="indirizzo_consegna" id="source2" class="form-control">
                                  </div>
                                @elseif($carr->mod_servizio == 3)
                                <div class="form-group">
                                    <label for="state">Punto di ritiro</label>  
                                    <input type="text" required name="indirizzo_ritiro" id="source1" class="form-control">
                                  </div>
                                  <hr>
                                  <div class="form-group">
                                    <label for="state">Punto di consegna</label>  
                                    <input type="text" required name="indirizzo_consegna" id="source2" class="form-control">
                                  </div>
                                  @else
                                  @endif
                                </div>

                              @endif
                            </div>
                            <div class="col-lg-6">
                                <div class="form-group">
                                    <label for="address">Data ritiro</label>
                                      <div id="dataritiroS" ></div>
                                      <div id="dataritiroN" ></div>

                                </div>
                                <div class="form-group">
                                     <label for="address">Data riconsegna</label>
                                      <div id="dataconsegnaS" required style="display:none"></div>
                                      <div id="dataconsegnaN" required style="display:none"></div>
                                </div>
                            </div>
                        </div>
                    </fieldset>
                    @else
                    <fieldset style="height:600px">
                        <legend>Ritiro scooter</legend>
                          <div class="row">
                            <div class="col-lg-6">
                              <div class="form-group" style="margin-top:50px">
                              <label for="state">Punto di ritiro</label>
                                <input type="text" readonly value="" readonly />
                            </div>
                              <hr>
                            <div class="form-group" style="margin-top:50px">
                              <label for="state">Punto di consegna</label>
                              <input type="text" readonly value=""/>
                            </div>                            
                          </div>
                        <div class="col-lg-6">
                          <div class="form-group">
                            <label for="address">Data ritiro</label>
                            <div id="dataritiro_geo" required></div>
                          </div>
                          <div class="form-group">
                            <label for="address">Data riconsegna</label>
                              <div id="dataconsegna_geo" required></div>
                          </div>
                        </div>
                      </div>
                    </fieldset>
                    @endif
                  @endforeach

and here is the javascript:

<script src="http://ift.tt/2a8rLkD"></script>
  <script>
$(document).ready(function(){
  var days = <?php echo json_encode($days); ?>;
  var dayx = <?php echo json_encode($dayx); ?>;
    $('[id="dataritiroS"]').datepicker({
      minDate : 0,
      beforeShowDay: function(date){
      var day = date.getDay();
        return [days.indexOf(day) !== -1];
    }});
    $('[id="dataritiroN"]').datepicker({
      minDate : 0,
      beforeShowDay: function(date){
      var dayz = date.getDay();
        return [dayx.indexOf(dayz) !== -1];
    }});
    $('[id="dataritiro_geo"]').datepicker({
      minDate : 0,
      beforeShowDay: function(date){
      var dayz = date.getDay();
        return [dayx.indexOf(dayz) !== -1];
    }});
    $('[id="dataconsegna_geo"]').datepicker({
      minDate : 0,
      beforeShowDay: function(date){
      var dayz = date.getDay();
        return [dayx.indexOf(dayz) !== -1];
    }});
});
  </script>
  <script>
$(document).ready(function(){
  var dayconsegnas = <?php echo json_encode($days); ?>;
  var dayconsegnax = <?php echo json_encode($dayx); ?>;
    $('[id="dataconsegnaS"]').datepicker({
      minDate : 0,
      beforeShowDay: function(date){
      var dayconsegna = date.getDay();
        return [dayconsegnas.indexOf(dayconsegna) !== -1];
    }});
    $('[id="dataconsegnaN"]').datepicker({
      minDate : 0,
      beforeShowDay: function(date){
      var dayconsegnaz = date.getDay();
        return [dayconsegnax.indexOf(dayconsegnaz) !== -1];
    }});
});
  </script>
<script type="text/javascript">
 $(document).ready(function () {
  $('#myModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget) // Button that triggered the modal
    var id_tariffa = button.data('tariffa') // Extract info from data-* attributes
      // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
      // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
    var modal = $(this)
        modal.find('.hidden input').val(id_tariffa)
});
    $( document).on("click", "#couponyes", function () {
        $('[id="ritiro"]').hide('fast');
        $('[id="azienda"]').show('fast');
        $('[id="dataritiroN"]').hide('fast');
        $('[id="dataritiroS"]').show('fast');
        $('[id="dataconsegnaN"]').hide('fast');
        $('[id="dataconsegnaS"]').show('fast');
        $('[id="tariffaN"]').hide('fast');
        $('[id="tariffaS"]').show('fast');
    });
    $( document).on("click", "#couponno", function () {
        $('[id="ritiro"]').show('fast');
        $('[id="azienda"]').hide('fast');
        $('[id="dataritiroN"]').show('fast');
        $('[id="dataritiroS"]').hide('fast');
        $('[id="dataconsegnaN"]').show('fast');
        $('[id="dataconsegnaS"]').hide('fast');
        $('[id="tariffaN"]').show('fast');
        $('[id="tariffaS"]').hide('fast');
    });
});
$('#cellulare').blur(function(evt) {
    evt.target.checkValidity();
}).bind('invalid', function(event) {
   alert('Il telefono deve contenere almeno 11 caratteri numerici');
});
</script>

This working on couponyes radio but on couponno only the first item of cicle is rendered...



via Chebli Mohamed

mardi 20 septembre 2016

RBAC managing permissions by role

I'm currently trying to make this work:

http://ift.tt/2cPVcrE

However, this doesn't seem to work out for me. So I want to be able to manage the permissions by role. Like Role 'member' needs to have specific perms, but if necessary, I want to be able to add or remove those permissions. I really don't know how I should fix this and I'm stuck at the moment I need to show if the user has the permission enabled or not.

This is my current code:

HTML:

<table class="table">
   <thead>
      <tr>
        <th>Naam</th>
        <th>Beschrijving</th>
        <th>Status</th>
        <th></th>
      </tr>
    </thead>
    <tbody>
      @foreach($getperms as $perm)
         <tr>
           <td></td>
           <td></td>
           <td><span class="label label-danger">Not enabled</span></td>
           <td><input type="checkbox" name=""></td>
          </tr>
       @endforeach
      </tbody>
</table>

And this is my controller:

/**
     * editUserPerms
     *
     * @return Response
     */
    public function editRolePerms($id)
    {
      $getrole = Role::find($id);

      $getperms = Permission::all();

      return view('admin.editroleperms')->with('role', $getrole)->with('getperms', $getperms);
    }

If someone could help me out with this, so I'm able to grant or revoke permissions and see if the permission is nabled or not would be awesome.e



via Chebli Mohamed

Laravel and mongodb aggregation

{ "_id" : ObjectId("57e0e23b06cb170c38001f32"), "rss_feed_id" : "57e0e1ea06cb170c38001f17", news_date" : "2016-09-12", "company_id" : ObjectId("57e0e1f206cb170c38001f18") }

{ "_id" : ObjectId("57e0e1ea06cb170c38001f17"), "rss_feed_id" : "57e0e1ea06cb170c38001f17", news_date" : "2016-09-12", "company_id" : ObjectId("57e0e1f206cb170c38001f18") }

{ "_id" : ObjectId("57e0e23b06cb170c38001f40"), "rss_feed_id" : "57e0e1ea06cb170c38001f17", news_date" : "2016-09-12", "company_id" : ObjectId("57e0e20a06cb170c38001f24") }

This is my mongodb data set. I need to search details depends on company_id using wherein condition using aggregation framework.



via Chebli Mohamed

what is the procedure for login authentication test case in phpunit larave 5?

what is the procedure for login authentication phpunit test cases in laravel 5 ?

$credentials=[
  'email'=>'admin@admin.com',
  'password'=>'admin'
];
$response=$this->call('POST','login',$credentials);
$this->assertTrue($response->isOk());



via Chebli Mohamed

lundi 19 septembre 2016

Laravel Change output of the view in controller

I need to change all @ in my parts of static and dynamic in view to [at]. So I have :

return view('myview')->with('items',Model::all());

When I try this my result is String :

return ChangeSymbols(view('myview')->with('items',Model::all()));

whats best way to change output of view in controller o any where .



via Chebli Mohamed

dimanche 18 septembre 2016

How Dynamically link assets in Laravel 5

I'm new to Laravel 5 i while searching over internet i for some basic concepts i found that in Laravel we can link assets dynamically i didn't understand how can we link them dynamically.

How can we know that an asset is used in certain point and include it in the view.

As per my knowledge i'm writing all the assets in one blade template and extending in views.

example.blade.php




custom view.blade.php

@extends('example)

But how come this do Dynamically?



via Chebli Mohamed

Laravel 5.1 Eloquent - referencing different schema from validation says that schema does not exist

I have a schema called public. Inside this schema I have a table called currencies.

<?php
declare(strict_types=1);

namespace Lapis\Domain\Currency;

use Lapis\Domain\Core\Database\Eloquent\Model;
use Lapis\Domain\Training\EloquentTraining;

/**
 * Class EloquentCurrency
 *
 * @package Lapis\Domain\Currency
 */
class EloquentCurrency extends Model implements CurrencyInterface
{
    /**
     * Indicates if the IDs are auto-incrementing.
     *
     * @var bool
     */
    public $incrementing = false;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'public.currencies';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'symbol',
        'code',
        'decimal_places',
    ];
}

Everything works perfectly due to setting $table as public.currencies. I can perform all CRUD operations through repository or directly in my controller.

What seems to be broken is trying to use exists rule.

In my validator I have:

'name' => [
    'required',
    'exists:public.currencies',
],

This is just an excerpt. Final validation will be much more complex but the issue is that Laravel is unable to see the table when I call it like public.currencies.

Apparently syntax

schema.table

doesn't work. Any ideas why? I can solve this my using custom validation and using custom repository method to check if exists but I wanted to use native method.

enter image description here



via Chebli Mohamed

samedi 17 septembre 2016

Persist a variable for the entire application in laravel

I am working on an application which aims to display records of students, obviously to see and edit a record I have to select a student. I would like to know how to store the id of the student in a global variable or something like that. To make it available in any part of the application to use it from any controller or view and once the user of the application close or display another record this variable is loaded with the new Id

Any idea how I could do this



via Chebli Mohamed

How to manually add ClassLoader in Laravel 5

I want add my class to classloader by this commands

$loader = new \Composer\Autoload\ClassLoader();
$loader->addPsr4('test\\', __DIR__ . '/../..' . '/modules/test');
$loader->register();

but dose not work and no error
dd($loader):

ClassLoader {#470 ▼
  -prefixLengthsPsr4: array:1 [▼
    "t" => array:1 [▶]
  ]
  -prefixDirsPsr4: array:1 [▼
    "test\" => array:1 [▼
      0 => "C:\wamp\www\app\Http\Controllers\admin/../../modules/test"
    ]
  ]
  -fallbackDirsPsr4: []
  -prefixesPsr0: []
  -fallbackDirsPsr0: []
  -useIncludePath: false
  -classMap: []
  -classMapAuthoritative: false
}



via Chebli Mohamed

Laravel project deploy

I have created a Laravel Project and I tried to upload it to my host which contains two domain..

The first domain is the main domain which contain a working website

The second domain which i want to deploy my Laravel Project in it

Here is the link http://ift.tt/2d1Jhg5 it gets me error 500 I don't know why!

What I am trying to do:

is to go to the public folder and be able to see my website normally.



via Chebli Mohamed

vendredi 16 septembre 2016

Bit Field in Schema Builder Laravel 5.3

I am following this article to search for the bit column type in Mysql Database Table

My Schema builder code is below.

if(!Schema::hasTable('tblrole')) {
    Schema::create('tblrole', function (Blueprint $table) {
        $table->integer('RoleID')->unsigned()->autoIncrement();
        $table->string('Role', 20);
        $table->boolean('IsActive')->default(false);
    });
}

I am concerned about column : IsActive which is right now Boolean type and get saved as tinyint in database.

Question

Is there any column type called bit in Laravel 5.3 Schema Builder? I just want to save two values for Active column. That is 0 or 1



via Chebli Mohamed

Auth login throttling not working in Laravel 5.2 in default auth

In routes.php

Route::post('/login', ['uses'=> 'Auth\AuthController@postLogin']);

In my AuthController

use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthUserController extends Controller
{
    use AuthenticatesAndRegistersUsers, ThrottlesLogins;
-------
    protected $maxLoginAttempts = 4;
    protected $lockoutTime = 300;

and thats it I am not overriding the post login just letting it use the default.

So, after trying more than 4 times also it's not throttling the request i.e. no error resonses for throttling. Please help.



via Chebli Mohamed

jeudi 15 septembre 2016

Laravel 5.1 , Downloading an image using REST Api

I am developing an API stack which will be consumed by android and iOS devices. one API method is supposed to be used to download an image from the server. I have used the followng code to initiate a download, but when i tested using Hurl, the method is forever returning 0 bytes.

if(file_exists($file)) //$file contains absolute path
            {
                EventLogger::info('##### Downloading the file#### ' );
                  $filename = basename($file);
                  $headers = array('Content-Type: image/png');
                response()->download($file,$filename,$headers);
            }

In the routes.php I have

Route::get('files/downloadimage/{cardid}', ['middleware'=>'jwt.auth', 'uses' => 'FilesController@downloadcardimage'])->name('files.download');

Please let me know if I am doing anything wrong.



via Chebli Mohamed

Why hasMany Relation still working even i removed relation in Laravel

enter image description here

enter image description here In the above both models i commented the method itemDestribution() but still it is working



via Chebli Mohamed

How can i display a table with two foreign keys in laravel

I have 3 tables

Users
-------------
user_id  (PK)
user_name

Items_distributed
-------------
user_id (FK) 
item_id(FK)

Item List
-----------------
item_id(PK)
item_name

Now i need to print Items_distributed table by taking both the user_id and item_id and dispaly their item_name and user_name

i dont know how to display both things at a time if i display either item_name or user_name its working but when i try to print both it is not working . Can any one solve my problem .



via Chebli Mohamed

Different css for different company - Laravel

I've made a website which has 1 design. There could be users with different roles. Roles are next :

  • normal user
  • admin of company
  • worker
  • ...

Each user on website has his company (in database its integer field) and i would like to make that each user with role - admin of company can change design of website for his company (for start colors of body, header, footer etc.). Example of that is that company 1 has yellow design, company 2 red etc. So far i have come up with idea to do it like this:

In table company expand table schema for additional columns (body_color-string, footer_color-string etc) and write values for each company into database.

After user is successfully logged then those values load from database in session and in my app.blade.php override css sections with session ones.

For example if i have div

<div class="test123">Something</div> 

I would override that value in my app.blade.php, if session is not set then apply default color white.

<style>
    .test123 {
        background-color:}
</style>

And this works, but it's kinda messy, so i would ask for some advice or improvement for later on (when i will have maybe height, width of some elements, etc)...

Am i doing it the right way, or this can be done even easier?



via Chebli Mohamed

mercredi 14 septembre 2016

JSON shows string type in behalf of bit/boolean field

{
  "Status": true,
  "Message": "Roles retrieved successfully",
  "Data": [
    {
      "RoleID": 1,
      "Role": "Super Admin",
      "IsPredefined": "1"
    }
  ]
}

I am fetching above results in json format. I am using below query to fetch the data from MySql database.

Select * form tblrole;

I am using PHP-Laravel 5.3

Is there any way to make the resultset like below.

{
  "Status": true,
  "Message": "Roles retrieved successfully",
  "Data": [
    {
      "RoleID": 1,
      "Role": "Super Admin",
      "IsPredefined": true
    }
  ]
}

Issue is in IsPredefined. I want to retrieve it Boolean type. In database it is of type bit



via Chebli Mohamed

Advanced Logging System Using Laravel

Hello I have a little dilemma, I need to create a logging system on an application that I've built that basically just logs users different activities such as "Created/Updated/Deleted" etc. I know this can be accomplished by doing something like the following

public function deleteUser($user_id)
{

    // Delete the user
    User::where('id', $user_id)->delete();

    // Log what action took place
    $log = new Log();
    $log->name   = $current_username;
    $log->action = 'Deleted User';
    $log->time   = Carbon::now();
    $log->save();

}

But using this method means that not only do i have to go to each event i want logging and add this code but any methods i make in the future will need to have this again.

My question is, is there any way to achieve logging more.. dynamically? I can't think of the appropriate logic.



via Chebli Mohamed

Laravel 5.1: Validation rule for unique datetime

I have a field that is a datetime and must be unique in the database. In the form, the user will inform a date in the format mm/dd/yyyy. So when I use the validation rule unique in the repository for the date field, it is ok because it consider the hour, minute and second. They always will be different.

Do you know if there is any validation rule that ignore the hour, minute and second for a datetime?

Thanks in advace.



via Chebli Mohamed

$HTTP_RAW_POST_DATA warning still showing up in POST response after setting 'always_populate_raw_post_data' in php.ini to -1

So i am using PHP 5.6 and building a Laravel 5.1 API and also building an android app.

When i try sending a post request from the android emulator i get the following message along with the proper data/response:

Deprecated: Automatically populating $HTTP_RAW_POST_DATA is deprecated and will be removed in a future version. 
To avoid this warning set 'always_populate_raw_post_data' to '-1' in php.ini and use the php://input stream instead. in Unknown on line 0
Warning: Cannot modify header information - headers already sent in Unknown on line 0.

I know why the error is showing up, but i cant seem to fix it.

The normal fix would be to set always_populate_raw_post_data to -1 but that is not working.

I am thinking of upgrading to a later version of php where $HTTP_RAW_POST_DATA has been removed.

any help/advice would be appreciated.



via Chebli Mohamed

mardi 13 septembre 2016

Updating MySQL database character set using Laravel

Is there a way to update a MySQL database character set using Laravel, perhaps the DB facade? I know I can just run the statement in something like MySQL Workbench, but I wanted to create a job that would run several updates to tables following the database update.

I wanted to run:

DB::statement("ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci");

But I'm getting an error:

SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll().

Is there a way I can accomplish what I'm trying to do or should I just run the statement separately from the job?



via Chebli Mohamed

How Can I change Default table for Auth::attempt() in laravel 5.0

I'm new to laravel and i am creating a authentication page i need to check the values for authentication in my own table but laravel is checking in users table

as my knowledge we can give in the user model

protected $table='my_own_table';

but i don't want to do this is there any way to change the default table of

Auth::attempt()

here is my code

function handleLogin(Request $request){
$data=$request->only('email','password');
if(\Auth::attempt($data))
{
   return "true";       
}
return "false";
}

in the above code when i excute it will check in the user table but i need to check in my_own_table is there any solution with out overriding the properties in the User model.



via Chebli Mohamed

How can I show captcha after 2 failed login attempts in Laravel?

How can I show captcha after 2 failed login attempts in Laravel ? I read the Throttle i protected maxLoginAttempts, how can I take it ? this is protected . please help . thanks all



via Chebli Mohamed

Laravel 5.1 belongs to many not working

I have following tables.

Users

id

name

Events

id

name

Cards

id

name

Transfers

id

event_id

card_id

I added the belongs to relationship in the Card.php as well as in Event.php

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

     public function events()
    {
        return $this->belongsToMany(Event::class,'transfers');
    }


}

class Event extends Model
{
        use SoftDeletes;

        protected $dates = ['deleted_at'];


    public function user()
    {
        return $this->belongsTo(User::class);
    }
    public function cards()
    {
        return $this->belongsToMany(Card::class,'transfers');
    }





}

I was trying to use the following statements in my controller both of them returned error

> echo count($user->events->cards->where([['id', '=',
> '57']])->find());die; //$cards is not defined.


> echo count($user->events->cards()->where([['id', '=',
> '57']])->find());die; // method cards() is not defined.I tried this after reading a tutorial

Any help on resolving this issue is appreciated.

Thanks in advance.



via Chebli Mohamed

lundi 12 septembre 2016

How to set no of Queue workers in laravel in windows and in shared server?

I am using Laravel 5.1, and I wanted to know if there is anyway with which we can increase the number of Queue workers in laravel... In its documentation, it's specified that we can do it by changing numprocs parameter with the help of Supervisor... But, how to do this on windows, as Supervisor is supported for only UNIX-based OS(es)... Also, Most probably, I will be deploying my application on Linux based shared server, so how to install supervisor there (because, server being shared, I don't think root access would be provided to me)??

Just for info, I am using database queue driver...

Thanks in Advance!



via Chebli Mohamed

Dom-pdf not rendering some characters

Im using vsmoraes/laravel-pdf for pdf generation. Its working fine for english characters but when its comes to other languages like chinese, greek its showing the ???? as below image

enter image description here

I have tried this one but went wrong. Anybody had this problem before?



via Chebli Mohamed

Laravel Queues for multi user environment

I am using Laravel 5.0, and I have a task that takes around 2 minutes to process, and this task particularly is generating a report...

Now, it is obvious that I can't make the user wait for 2 minutes on the same page where I took user's input, instead I should process this task in the background and notify the user later about task completion...

So, to achieve this, Laravel provides Queues that runs the tasks in background (If I didn't understand wrong), Now for multi-user environment, i.e. if more than one user demands report generation (say there are 4 users), so being the feature named Queues, does it mean that tasks will be performed one after the other (i.e. when 4 users demand for report generation one after other, then 4th user's report will only be generated when report of 3rd user is generated) ??

If Queues completes their tasks one after other, then is there anyway with which tasks are instantly processed in background, on request of user, and user can get notified later when its task is completed??



via Chebli Mohamed

TokenMismatchException in VerifyCsrfToken in Laravel 5.1 + angular

I have Laravel 5.1 + angular form sending JSON request when user want to send mail from website feedback form.

I did my form according to documentation here http://ift.tt/2cmWmgK and anyway I get error message TokenMismatchException in VerifyCsrfToken.php line 53:

I found a lot of topics on stackoverflow, but no real solution. Is there?

in header of my layout I have

<meta name="csrf-token" content="{!! csrf_token() !!}">
<script>
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
</script>

then in my form I have this

        <form name="callback" ng-controller="callbackController" role="form" class="" enctype="multipart/form-data">
          {!! csrf_field() !!}
    ...
    ...
<button type="submit" class="btn btn-primary pull-right" ng-click="submit(callback.$valid)" ng-bind="submittext" ng-class="{ 'btn-danger': callback.name.$touched && callback.name.$invalid || callback.tel.$touched && callback.tel.$invalid, 'btn-success': callback.name.$touched && callback.name.$valid && callback.tel.$touched && callback.tel.$valid, }">Send</button>

    </form>



via Chebli Mohamed

How to upgrade Laravel 5.0.* to 5.2.* or later

My Application is built with Laravel version 5.0.35 and I want it to update to version 5.2.*

How can I do this?? Can I just replace '5.0.*' to '5.2.*' in composer.json file and then command composer update, will this work?? If not, then is there any way with which I can upgrade easily and automatically?? Please guide me step by step if possible...



via Chebli Mohamed

How to define a "Master Layout" in Laravel 5.1

I'm starting to use Laravel 5.1 from 4.2 and I have a question about the definition of layouts in the controller.

In 4.2 I have this

private $layout = 'layouts.master';

    public function showWelcome()
    {
        $this->layout->content =  View::make('home');
    }

So when the view load, in the

@yield('section')

of the "master.blade.php" in the layouts folder will appears the view "Home"

I search how to use this in 5.1 and I see that the asignation of the layout.masters as been removed, but I can't see the new usage anywhere.

Now in 5.1 I have

namespace App\Http\Controllers;

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

class HomeController extends BaseController {

    public function showWelcome()
    {
        return view('home');
    }
}

How Can I say to the function showWelcome that it have to yield the content with the view?

Sorry for my bad english.



via Chebli Mohamed

Laravel 5.1 Find an item using eloquent

I have following tables.

Users

id

name

Events

id

name

Cards

id

name

Transfers

id

event_id

card_id

An user has many events and cards. An user can accepts cards from other user which he met at an event.A row will be added under transfers table whenever a card is accepted by a user, this row links a card_id with event_id. I am looking for a way to check a card (card_id) is added under the transfers table for a logged in user's event(event_id).

eg:-

auth()->user()->events->transfers->where(([['card_id', '=',$cardid]])->find());

Can someone help me by telling what is the best way to handle above situation using eloquent?



via Chebli Mohamed

Laravel 5.1 loginUsingId() with linkedin account (using socialite) failed in Authenticate middleware

I'm using Laravel 5.1 and try implements login with LinkedIn to my app. The OAuth 2 login process working fine and I manage to add a new user to users table with the correct details. I can manage to log this user in using Laravel loginUsingId() function as well (i can see \Auth::user() after it) but it fails in the Authenticate middleware.

This is the providerExecute function in my AuthController:

 public function providerExecute($provider, Request $request, $token)
{
    if(!is_null($token)){
        session(['invitation_token' => $token]);
    }
    if (!$request->has('code')) {
        return $this->getAuthFirst($provider);
    }
    $user = Socialite::with($provider)->user();
    if ($user) {
        $pid = $user->id;
        $exists = User::where('email', $user->email)->first();
        if ($exists) {
            Auth::loginUsingId((int)$exists->id,true); //when dd() the \Auth::user() here - it's returns the user data
            return redirect('home');
        }
        $new_user = new User();
        if (session('invitation_token')) {
            $invitation = $this->getUserInvitation(session('invitation_token'));
            if(!is_null($invitation->client_id)){
                $client = Client::findOrFail($invitation->client_id);
                if(!$this->canAddUsers($client)){
                    Log::info('Register from invitation! Client ' . $client->name . ' reached max users count, client id: ' . $client->id);
                    return response()->view('errors.auth',
                        ['error' => 'Error! Reached users limit, to add more users please upgrade your account plan']);
                }
            }
            $new_user->client_id = $invitation->client_id;
            $new_user->agency_id = $invitation->agency_id;
            $new_user->auth_level = $invitation->auth_level;
            $invitation->active = 0;
            $invitation->save();
            $redirect_path = "verification/send/";
        }else{
            $new_user->auth_level = config('LM2.ADMIN_AUTH_LEVEL');
            $redirect_path = "welcome/send/";
        }
        $new_user->name = $user->name;
        $new_user->email = $user->email;
        $new_user->provider_id = $user->id;
        $new_user->provider_token = $user->token;
        $new_user->img_src = $user->avatar ? $user->avatar : $this->getDefaultAvatarSrc();
        $new_user->account_verified = 1;
        $new_user->save();
        Auth::loginUsingId($new_user->id);
        return redirect($redirect_path.$new_user->id);
    }else{
        abort('403' , 'Unauthorized.');
    }
}

And this is the Authenticate middleware:

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


public function handle($request, Closure $next)
{
    //When dd($this->auth->user()) - returns null;
    if (!$this->auth->user()) {
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('login') ;
        }
    }elseif(!$this->auth->user()->active){
        $this->auth->logout();
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('login')->withErrors(['Inactive User']);
        }
    }

    return $next($request);
}

Anyone know the reason it's happans and what can be the solution for it? thank's a lot!



via Chebli Mohamed

Laravel Autocomplete not working

I have implemented a Laravel 5.1 autocomplete function using following codes:

snippet js

<script type="text/javascript"> 
 $(document).ready(function () {
  $("#utente").autocomplete({
    minLength:3,
    autoFocus: true,
    source: '',
    select: function( event, ui ) {
        window.location.href = ui.item.url;
    },

});
});

</script>

This is my Route:

Route::any('utente', function(){


 $term = Input::get('utente');
 // 4: check if any matches found in the database table 
 $data = DB::table("tb_users")->distinct()->where('last_name', 'LIKE', $term.'%')->groupBy('last_name')->get();
 foreach ($data as $v) {
 $nome = $v->last_name . ' ' . $v->first_name;
 $url = "clienti?utente=$v->id";
 $return_array[] = array('value' => $nome, 'label' => $nome, 'url' => $url);  }
  // if matches found it first create the array of the result and then convert it to json format so that 
  // it can be processed in the autocomplete script
 return Response::json($return_array);
 });

And this is the fiedl used for rendere the autocomplete.

<input type="text" id="utente" name="utente" placeholder="Cognome e Nome" class="form-control-utente" ></input>

The problem is that this fetch all the results in DB... and not the results that match the query



via Chebli Mohamed

dimanche 11 septembre 2016

Laravel excel export - string formatted column showing as number

In localhost i can set the column format as PHPExcel_Cell_DataType::TYPE_STRING and its working fine here is the .xls file by using this type

enter image description here

how ever if i test this in live i get something like enter image description here

column values set to 0.

Why i have tried PHPExcel_Cell_DataType::TYPE_STRING format is because the string like 65081035703021 showing as number (base 10) in ms-excel

Whats goes wrong for me?

enter image description here



via Chebli Mohamed

nested categories routing in Laravel 5.1

I have catalog with 4 nested categoies levels. Each subcategory could have items and/or nested categories. As long as I walking on the subcategory pages everything is OK. But when I try to go to item page, then I get ModelNotFoundException, because Laravel cannot understand that it is not category anymore.

-Catalog     (instance of Category model level 1)
--Cat1       (instance of Category model level 2)
--Product1   (instance of Item model)
--Product2
--Product3
...
--Cat2       (instance of Category model level 2)
---Product1  (instance of Item model)
---Product2
---Product3
...
---Cat3      (instance of Category model level 3)
----Product1 (instance of Item model)
----Product2
----Product3
...
----Cat3      (instance of Category model level 4)
-----Product1 (instance of Item model)
-----Product2
-----Product3

routes.php

    Route::get('catalog', ['as' => 'catalog.index', 'uses' => 'CatalogController@getIndex']);
    Route::get('catalog/{category}', ['as' => 'catalog.cat', 'uses' => 'CatalogController@getCategory'])->where(['category' => '.*']);
    // {category} could be equal to 'doors' or 'doors/glass' or unfinite number of sublevels
    Route::get('catalog/{category}/{item}', ['as' => 'catalog.item', 'uses' => 'CatalogController@getItem']);
    // this route is never working, because laravel always render {category}/{item} as {category} 

RouteServiceProvider.php

public function boot(Router $router)
{
    parent::boot($router);

    Route::bind('category', function($cat) {
        $bread = explode("/", substr($cat, 0));
        $sef = array_pop($bread);
        return Category::whereSef($sef)->firstOrFail();
    });


}

Every category in database has sef which is not equal to path
Example: url = http://ift.tt/2cmQx0j
Sef for glass = glass (not catalog/doors/glass)
That is why I use explode in RouteServiceProvider to catch sef of element after last slash.

The problem is when I have url for the item then I have following error

ModelNotFoundException in Builder.php line 223: No query results for model [App\Category].

This happens because in URL http://ift.tt/2c7ZEov laravel still looking door1 in Category model not in Item model. But I don't know what to do to explain laravel that $category is finished now.



via Chebli Mohamed

samedi 10 septembre 2016

How to remove public word from laravel URL

Currently I am using Shared Web Hosting, and uploaded my Laravel project (developed in Laravel 5.1), but I have to type to public with domain name. eg: http://ift.tt/2cf4grG

My Hosting seller not mapping my domain to laravel public folder so Its mapped to public_html folder.

Is there any way available to remove public word from URL? I tried to keep my files in public_html folder and moved public folder out of `public_html' folder, but no luck,

Kindly guideme



via Chebli Mohamed

vendredi 9 septembre 2016

Laravel 5.1 send email (Connection could not be established with host smtp.gmail.com [connection time out #110]

I'm learning Laravel 5.1 mail for my project. So, I try to send simple email first from a new Laravel 5.1 application on my localhost.

this is my .env config file

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=mygmail@gmail.com
MAIL_PASSWORD=mygmailpassword
MAIL_ENCRYPTION=tls

and this is my config/mail.php

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

'host' => env('MAIL_HOST', 'smtp.mailgun.org'),

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

'from' => ['address' => 'sender@gmail.com', 'name' => 'Sender'],

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

'username' => env('MAIL_USERNAME'),

'password' => env('MAIL_PASSWORD'),

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

this is my function to send the email

Mail::send('emails.email', ['user'=>'Sender'], function($m){

    $m->to('receiver@yahoo.com','receiver')->subject('subject');
});

With this, when I run the application, it always return the error

Swift_TransportException in StreamBuffer.php line 265:

Connection could not be established with host smtp.gmail.com [Connection timed out #110]

What I've tried:

  • Turn on 'less secure apps' on google account
  • 2-step verification (generate an app password) and use it on (MAIL_PASSWORD on .env config)

But, none of this succeed. What am I doing wrong here?

PS: My OS is Linux Ubuntu 14.04



via Chebli Mohamed

Duplicate records in User's Session Maangement

For the User Session Management, I set the SESSION_DRIVER=database and in database there is session table.

Schema::create('tblsession', function ($table) {
    $table->string('id')->unique();
    $table->integer('user_id')->nullable();
    $table->string('ip_address', 45)->nullable();
    $table->text('user_agent')->nullable();
    $table->text('payload');
    $table->integer('last_activity');
});

Here issue is: whenever i login, it keep creating the new User's Session records. I am using same Chrome browser and same Tab.

Did I miss anything in doing the configuration? I am following Session Management as described here



via Chebli Mohamed

Updated Laravel 5.2 - No Auth

I developed a application in Laravel 5.1 and i needed make a laravel update to 5.2.

Now that i finished, i can not make a Auth, every time return false.

App.php

 'providers' => [

    /*
     * Laravel Framework Service Providers...
     */
    Illuminate\Foundation\Providers\ArtisanServiceProvider::class,
    Illuminate\Auth\AuthServiceProvider::class,
    // Sarav\Multiauth\MultiauthServiceProvider::class,
    Illuminate\Broadcasting\BroadcastServiceProvider::class,
    Illuminate\Bus\BusServiceProvider::class,
    Illuminate\Cache\CacheServiceProvider::class,
    Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
    // Illuminate\Routing\ControllerServiceProvider::class,
    Illuminate\Cookie\CookieServiceProvider::class,
    Illuminate\Database\DatabaseServiceProvider::class,
    Illuminate\Encryption\EncryptionServiceProvider::class,
    Illuminate\Filesystem\FilesystemServiceProvider::class,
    Illuminate\Foundation\Providers\FoundationServiceProvider::class,
    // Illuminate\Hashing\HashServiceProvider::class,
    App\Providers\ShaHashServiceProvider::class,
    Illuminate\Mail\MailServiceProvider::class,
    Illuminate\Pagination\PaginationServiceProvider::class,
    Illuminate\Pipeline\PipelineServiceProvider::class,
    Illuminate\Queue\QueueServiceProvider::class,
    Illuminate\Redis\RedisServiceProvider::class,
    Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
    Illuminate\Session\SessionServiceProvider::class,
    Illuminate\Translation\TranslationServiceProvider::class,
    Illuminate\Validation\ValidationServiceProvider::class,
    Illuminate\View\ViewServiceProvider::class,

    Collective\Html\HtmlServiceProvider::class,

    // Captcha
    Mews\Captcha\CaptchaServiceProvider::class,

    /*
     * Application Service Providers...
     */
    App\Providers\AppServiceProvider::class,
    App\Providers\AuthServiceProvider::class,
    App\Providers\EventServiceProvider::class,
    App\Providers\RouteServiceProvider::class,
    App\Providers\ViewServiceProvider::class,

],

/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/

'aliases' => [

    'App'       => Illuminate\Support\Facades\App::class,
    'Artisan'   => Illuminate\Support\Facades\Artisan::class,
    'Auth'      => Illuminate\Support\Facades\Auth::class,
    'Blade'     => Illuminate\Support\Facades\Blade::class,
    'Bus'       => Illuminate\Support\Facades\Bus::class,
    'Cache'     => Illuminate\Support\Facades\Cache::class,
    'Config'    => Illuminate\Support\Facades\Config::class,
    'Cookie'    => Illuminate\Support\Facades\Cookie::class,
    'Crypt'     => Illuminate\Support\Facades\Crypt::class,
    'DB'        => Illuminate\Support\Facades\DB::class,
    'Eloquent'  => Illuminate\Database\Eloquent\Model::class,
    'Event'     => Illuminate\Support\Facades\Event::class,
    'File'      => Illuminate\Support\Facades\File::class,
    'Gate'      => Illuminate\Support\Facades\Gate::class,
    'Hash'      => Illuminate\Support\Facades\Hash::class,
    'Input'     => Illuminate\Support\Facades\Input::class,
    'Inspiring' => Illuminate\Foundation\Inspiring::class,
    'Lang'      => Illuminate\Support\Facades\Lang::class,
    'Log'       => Illuminate\Support\Facades\Log::class,
    'Mail'      => Illuminate\Support\Facades\Mail::class,
    'Password'  => Illuminate\Support\Facades\Password::class,
    'Queue'     => Illuminate\Support\Facades\Queue::class,
    'Redirect'  => Illuminate\Support\Facades\Redirect::class,
    'Redis'     => Illuminate\Support\Facades\Redis::class,
    'Request'   => Illuminate\Support\Facades\Request::class,
    'Response'  => Illuminate\Support\Facades\Response::class,
    'Route'     => Illuminate\Support\Facades\Route::class,
    'Schema'    => Illuminate\Support\Facades\Schema::class,
    'Session'   => Illuminate\Support\Facades\Session::class,
    'Storage'   => Illuminate\Support\Facades\Storage::class,
    'URL'       => Illuminate\Support\Facades\URL::class,
    'Validator' => Illuminate\Support\Facades\Validator::class,
    'View'      => Illuminate\Support\Facades\View::class,
    'Form'      => Collective\Html\FormFacade::class,
    'Html'      => Collective\Html\HtmlFacade::class,
    'Captcha'   => Mews\Captcha\Facades\Captcha::class

],

routes.php

Route::group(['middleware' => ['web']], function () {
    Route::get('/', function(){

        dd( Auth::attempt(['email' => 'campos@company.com.br', 'senha' => '1234567890' ] ) );

    });
});

Auth.php

return [

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' =>  App\Clientes::class,
        ],
        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],
];

Aditional info: My laravel not has the default de hash (bcrypt), i'm using Shahash.

(When i used the Laravel 5.1, all work fine ... Before Upgrade to 5.2 the Auth not working....)

I create a new customer to test register and login. The password has encrypt with shahash, all ok. But on Auth never return True



via Chebli Mohamed

Dompdf is not working in laravel 5.1's console/kernel.php

Css float is not working while running the function inside Kernel.php

But it works properly in normal controller function.

This is kernel.php

    $schedule->call(function () {

        $poolMail = EmailPool::where('status', 0)->get();
        foreach($poolMail as $p)
        {
        $this->createReservationPdf($content['rcode']);
        }

    })->everyMinute();



    public function createReservationPdf($resId)
{
    $rsvData = \App\Reservation::where('reservation_code', $resId)->first();
    $rsvPayment = \App\ReservationPayment::where('reservation_code', $resId)->first();
    $rsvExtras = \App\RsvExtra::where('r_no', $resId)->get();
    $rsvInsurances = \App\RsvInsurance::where('r_no', $resId)->get();

    $pStation = \App\Station::where('istasyon_kodu', $rsvPayment->pstation)->first();
    $rStation = \App\Station::where('istasyon_kodu', $rsvPayment->rstation)->first();
    $carGroup = \App\Group::where('grp', $rsvPayment->vgroup)->first();


    $pdf = \PDF::loadView('pdf.test', compact('rsvData', 'rsvPayment', 'rsvExtras', 'rsvInsurances', 'pStation', 'rStation', 'carGroup'));
    return $pdf->save(storage_path().'/'.$resId.'.pdf');
}

And createReservationPdf is working well in any other controller.

Actually, it was working until a couple of days ago.



via Chebli Mohamed

Laravel 5.1 Session expires after a few requests

I'm using Laravel 5.1 with Jessengers for my web application. I have explored this issue many times over here, on Github and Laracasts but still stuck in solving this. I'm using SESSION_DRIVER=file in my environment file, also tried increasing 'lifetime' => 120, to let's say 1200, however, I know that's in minutes but that was a try. My session doesn't even last for one minute. Here's my session.php file.

    return [

    /*
    |--------------------------------------------------------------------------
    | Default Session Driver
    |--------------------------------------------------------------------------
    |
    | This option controls the default session "driver" that will be used on
    | requests. By default, we will use the lightweight native driver but
    | you may specify any of the other wonderful drivers provided here.
    |
    | Supported: "file", "cookie", "database", "apc",
    |            "memcached", "redis", "array"
    |
    */

    'driver' => env('SESSION_DRIVER', 'file'),

    /*
    |--------------------------------------------------------------------------
    | Session Lifetime
    |--------------------------------------------------------------------------
    |
    | Here you may specify the number of minutes that you wish the session
    | to be allowed to remain idle before it expires. If you want them
    | to immediately expire on the browser closing, set that option.
    |
    */

    'lifetime' => 120,

    'expire_on_close' => false,

    /*
    |--------------------------------------------------------------------------
    | Session Encryption
    |--------------------------------------------------------------------------
    |
    | This option allows you to easily specify that all of your session data
    | should be encrypted before it is stored. All encryption will be run
    | automatically by Laravel and you can use the Session like normal.
    |
    */

    'encrypt' => false,

    /*
    |--------------------------------------------------------------------------
    | Session File Location
    |--------------------------------------------------------------------------
    |
    | When using the native session driver, we need a location where session
    | files may be stored. A default has been set for you but a different
    | location may be specified. This is only needed for file sessions.
    |
    */

    'files' => storage_path('framework/sessions'),

    /*
    |--------------------------------------------------------------------------
    | Session Database Connection
    |--------------------------------------------------------------------------
    |
    | When using the "database" or "redis" session drivers, you may specify a
    | connection that should be used to manage these sessions. This should
    | correspond to a connection in your database configuration options.
    |
    */

    'connection' => null,

    /*
    |--------------------------------------------------------------------------
    | Session Database Table
    |--------------------------------------------------------------------------
    |
    | When using the "database" session driver, you may specify the table we
    | should use to manage the sessions. Of course, a sensible default is
    | provided for you; however, you are free to change this as needed.
    |
    */

    'table' => 'sessions',

    /*
    |--------------------------------------------------------------------------
    | Session Sweeping Lottery
    |--------------------------------------------------------------------------
    |
    | Some session drivers must manually sweep their storage location to get
    | rid of old sessions from storage. Here are the chances that it will
    | happen on a given request. By default, the odds are 2 out of 100.
    |
    */

    'lottery' => [0, 100],

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Name
    |--------------------------------------------------------------------------
    |
    | Here you may change the name of the cookie used to identify a session
    | instance by ID. The name specified here will get used every time a
    | new session cookie is created by the framework for every driver.
    |
    */

    'cookie' => 'laravel_session',

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Path
    |--------------------------------------------------------------------------
    |
    | The session cookie path determines the path for which the cookie will
    | be regarded as available. Typically, this will be the root path of
    | your application but you are free to change this when necessary.
    |
    */

    'path' => '/',

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Domain
    |--------------------------------------------------------------------------
    |
    | Here you may change the domain of the cookie used to identify a session
    | in your application. This will determine which domains the cookie is
    | available to in your application. A sensible default has been set.
    |
    */

    'domain' => null,

    /*
    |--------------------------------------------------------------------------
    | HTTPS Only Cookies
    |--------------------------------------------------------------------------
    |
    | By setting this option to true, session cookies will only be sent back
    | to the server if the browser has a HTTPS connection. This will keep
    | the cookie from being sent to you if it can not be done securely.
    |
    */

    'secure' => false,

];



via Chebli Mohamed