jeudi 31 décembre 2015

Laravel 5 authentication middleware always redirects to root or login

When I protect routes in Laravel 5 it works well when I'm not logged in because it redirects the protected routes to the login page but once I login and try to access the protected routes it redirects me to the root route. For example if I try to access /people or /people/1 it will redirect me to /

Here's my routes.php file:

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

Route::group(['middleware' => ['auth']], function () {
 Route::resource('people', 'PeopleController');
 Route::resource('people.checkins', 'CheckinsController');
 Route::model('checkins', 'Checkin');
 Route::model('people', 'Person');

 Route::bind('checkins', function($value, $route) {
    return App\Checkin::whereId($value)->first();
 });
 Route::bind('people', function($value, $route) {
    return App\Person::whereId($value)->first();
 });
});

Route::group(['middleware' => 'web'], function () {
 Route::auth();

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



via Chebli Mohamed

Can't install Laravel cashier

The first error I had was php version wasn't up to date, so when I updated it, I receive this:

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: remove laravel/framework v5.0.34
    - Conclusion: don't install laravel/framework v5.0.34
    - Conclusion: don't install laravel/framework v5.0.33
    - Conclusion: don't install laravel/framework v5.0.32
    - Conclusion: don't install laravel/framework v5.0.31
    - Conclusion: don't install laravel/framework 5.0.30
    - Conclusion: don't install laravel/framework v5.0.29
    - Conclusion: don't install laravel/framework v5.0.28
    - Conclusion: don't install laravel/framework v5.0.27
    - Conclusion: don't install laravel/framework v5.0.26
    - Conclusion: don't install laravel/framework v5.0.25
    - Conclusion: don't install laravel/framework v5.0.24
    - Conclusion: don't install laravel/framework v5.0.23
    - Conclusion: don't install laravel/framework v5.0.22
    - Conclusion: don't install laravel/framework v5.0.21
    - Conclusion: don't install laravel/framework v5.0.20
    - Conclusion: don't install laravel/framework v5.0.19
    - Conclusion: don't install laravel/framework v5.0.18
    - Conclusion: don't install laravel/framework v5.0.17
    - Conclusion: don't install laravel/framework v5.0.16
    - Conclusion: don't install laravel/framework v5.0.15
    - Conclusion: don't install laravel/framework v5.0.14
    - Conclusion: don't install laravel/framework v5.0.13
    - Conclusion: don't install laravel/framework v5.0.12
    - Conclusion: don't install laravel/framework v5.0.11
    - Conclusion: don't install laravel/framework v5.0.10
    - Conclusion: don't install laravel/framework v5.0.9
    - Conclusion: don't install laravel/framework v5.0.8
    - Conclusion: don't install laravel/framework v5.0.7
    - Conclusion: don't install laravel/framework v5.0.6
    - Conclusion: don't install laravel/framework v5.0.5
    - Conclusion: don't install laravel/framework v5.0.4
    - Conclusion: don't install laravel/framework v5.0.3
    - Installation request for laravel/cashier ~6.0 -> satisfiable by laravel/cashier[v6.0.0].
    - Conclusion: don't install laravel/framework v5.0.2
    - Conclusion: don't install laravel/framework v5.0.1
    - laravel/cashier v6.0.0 requires illuminate/database ~5.1 -> satisfiable by illuminate/database[v5.1.1, v5.1.13, v5.1.16, v5.1.2, v5.1.20, v5.1.22, v5.1.25, v5.1.28, v5.1.6, v5.1.8, v5.2.0].
    - don't install illuminate/database v5.1.1|don't install laravel/framework v5.0.0
    - don't install illuminate/database v5.1.13|don't install laravel/framework v5.0.0
    - don't install illuminate/database v5.1.16|don't install laravel/framework v5.0.0
    - don't install illuminate/database v5.1.2|don't install laravel/framework v5.0.0
    - don't install illuminate/database v5.1.20|don't install laravel/framework v5.0.0
    - don't install illuminate/database v5.1.22|don't install laravel/framework v5.0.0
    - don't install illuminate/database v5.1.25|don't install laravel/framework v5.0.0
    - don't install illuminate/database v5.1.28|don't install laravel/framework v5.0.0
    - don't install illuminate/database v5.1.6|don't install laravel/framework v5.0.0
    - don't install illuminate/database v5.1.8|don't install laravel/framework v5.0.0
    - don't install illuminate/database v5.2.0|don't install laravel/framework v5.0.0
    - Installation request for laravel/framework 5.0.* -> satisfiable by laravel/framework[5.0.30, v5.0.0, v5.0.1, v5.0.10, v5.0.11, v5.0.12, v5.0.13, v5.0.14, v5.0.15, v5.0.16, v5.0.17, v5.0.18, v5.0.19, v5.0.2, v5.0.20, v5.0.21, v5.0.22, v5.0.23, v5.0.24, v5.0.25, v5.0.26, v5.0.27, v5.0.28, v5.0.29, v5.0.3, v5.0.31, v5.0.32, v5.0.33, v5.0.34, v5.0.4, v5.0.5, v5.0.6, v5.0.7, v5.0.8, v5.0.9].

Does anyone know what it means and how to fix it so cashier will install successfully?



via Chebli Mohamed

laravel5.1 validate number

How to validate numbers using laravel validator. In my case I need to validate if a number is between "1.00" and "50.00".

As seperator between the number pairs the "." and the "," should be allowed. The number should have only two decimal places. Is there a way to get this done using standart laravel validators combined?

using a regex, the regex should match these requirements:

starting with 0-9 (2 numbers are possible)

followed by one . or one ,

followed with 0-9 (2 numbers are possible)

OR simple numbers like 1-9 with NO dots and NO commas

numbers between 1 and 50 should be allowed in total. This regex should be used for a prepaid system where users should be able to topup their accounts from 1 to 50. For this reason entries like 1.00 and 1,00 should be valid as well as 1 or 2. 50.00 is the maximum of amount. 1.00 the minimum.



via Chebli Mohamed

Token Mismatch issue in IFrame in Internet Explorer. Laravel 5.2

What's the problem ?

I am facing Token Mismatch issue when accessing the site in IFrame in Internet Explorer.


What I tried so far ?

I search for the resolution and found this link

Below is the code that I found in the above link

App::after(function ($request,$response){
    if($request->is('external/*')){
        // IE iframe cookie fix
        $response->header('P3P', 
                  'CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
    }
});


What's the question ?

Where should I write the above code in Laravel 5.2 ?



via Chebli Mohamed

Laravel 5.2 Auth not Working

As you guys know Laravel 5.2 was released a few days ago. I am trying this new version. I made a new project using the following command on CLI:

laravel new testapp

As per documentation of Authentication Quickstart, I followed the following command to scaffold routes and views of authentication:

php artisan make:auth

It worked fine. Registration is working fine. But I am facing problem in Login. After login I tested following in route.php file:

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

Auth::user() is returning null and also Auth::check() and Auth::guest() are not working appropriately. I have tried same thing again and again two three times by making new projects but couldn't get the correct results.

Below is the complete route.php.

    <?php

/*
|--------------------------------------------------------------------------
| Routes File
|--------------------------------------------------------------------------
|
| Here is where you will register all of the routes in an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

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

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/

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

Route::group(['middleware' => 'web'], function () {
    Route::auth();

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

Can anyone help me? or Is anyone facing the same problem? How can I fix it?



via Chebli Mohamed

Laravel 5.2 ErrorException in Request.php line 775: Session store not set on request

I am having problem in Laravel 5.2 which is input value with the curry bracket

Code Below :

<input type="text" name="name" id="name" class="form-control" value="{{ old('name') }}">



via Chebli Mohamed

PHPWord unable to load *.doc (97-2003 MS Word) document files

I am trying to load 97-2003 MS Word documents but the following error keeps showing up.

image

Following is simply an adaptation of the code provided in the Sample_11_ReadWord97.php file:

    $source = "OldDoc.doc";
    echo "Reading document ".$source."<br><br>";
    if(str_contains($source, '.docx'))
        $phpWordObj = IOFactory::load($source);
    elseif(str_contains($source, '.doc'))
        $phpWordObj = IOFactory::load($source, 'MsDoc');
    echo "Document reading complete";

I am using Laravel 5.1 and docx files seem to load just fine. Any idea where I might be going wrong with this?



via Chebli Mohamed

date format in laravel 5

how to get records between current date to next 30 days in laravel 5? Here is the code i used for that.

public static function getNextInspections() 
{
$inspection = DB::table('inspection');
$inspection->select('*');
$inspection ->where('inspection.next_inspection_date', DB::raw('BETWEEN NOW() AND DATE_ADD(NOW(),INTERVAL 30 DAY)'));
return $inspection->get();

}

I don't get proper answer in laravel 5. but I got the answer in mysql. Given below is the MySQL command i used:

"select equipment_id, next_inspection_date,deleted_at from inspection where next_inspection_date BETWEEN NOW() AND DATE_ADD(now(), INTERVAL 30 DAY);"

Can anyone help me with?



via Chebli Mohamed

Html tags showing after ckeditor

Im using ckeditor CDN in my laravel project.I've got the editor to show up on the text area but after I submit the form,texts from the textarea displays along with html tags. Am i missing anything?

<head>
   <link rel="stylesheet" href="http://ift.tt/1RrshYi">
         <script src="//cdn.ckeditor.com/4.5.6/standard/ckeditor.js"></script>
    <title>project title </title>
  </head>

Form view:

<div class="form-goup">
{!!Form::label('details','details')!!}
{!!Form::textarea('details',null,['class'=>'form-control'])!!}

<script>
        ckeditor.replace( 'details' );
    </script>

show view:

{{$pages->details}}

output: output



via Chebli Mohamed

trying to get property of non object, laravel 5?

here, i retrieve two tables to be displayed on one view page. the images is in the users table. when i clicked profile tab, it displayed error message : Trying to get property of non-object. what are wrong with my codes referring to the error message.

upload.blade.php

<div id="templatemo_sidebar">
<tr>
    <div id="login">logged in as :</div>
</tr>
@foreach($users as $users)
<div id="img">
    <img src="{!! '/profiles/'.$users->filePath !!}">{{$users->filePath}}
</div>
@endforeach
    {!! Form::open(['action'=>'ProfileController@store', 'files'=>true]) !!}
    <div class="form-group">
        {!! Form::label('image', 'Choose an image') !!}
        {!! Form::file('image') !!}
    </div>

    <div class="form-group">
        {!! Form::submit('Save', array( 'class'=>'btn btn-danger form-control' )) !!}
    </div>

    {!! Form::close() !!}
@foreach($profiles as $profile)
    <div id="profile_sidebar">
        <tr>
            <td>{{$profile->student_name}}</td>
        </tr>
        <tr>
            <td>{{$profile->student_id}}</td>
        </tr><br>
        <tr>
            <td>{{$profile->student_ic}}</td>
        </tr>
        <tr><br>
            <td><mark>Status : {{$profile->status}}</mark></td>
        </tr>

        @endforeach

    </div>

ProfileController.php

  public function store(Request $request)
{
    $users = Auth::user();
    if($request->hasFile('image')) {
        $file = Input::file('image');
        //getting timestamp
        //$timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
        //$name = $timestamp. '-' .$file->getClientOriginalName();
        $name=$file->getClientOriginalName();
        $users->filePath = $name;

        $file->move(public_path().'/profiles/', $name);
    }
    $users->save();
    $users = Auth::user();
    $users = Profile::where('student_id', $users->student_id)->get();
    $profiles = Profile::all();
    return view('profile', compact('users', 'profiles'));
}

}



via Chebli Mohamed

Laravel 5.2 Auth::guest cant work

 @if (Auth::guest())
                    <li><a href="{{ url('/login') }}">Login</a></li>
                    <li><a href="{{ url('/register') }}">Register</a></li>
                @else
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
                            {{ Auth::user()->name }} <span class="caret"></span>
                        </a>

                        <ul class="dropdown-menu" role="menu">
                            <li><a href="{{ url('/logout') }}"><i class="fa fa-btn fa-sign-out"></i>Logout</a></li>
                        </ul>
                    </li>
                @endif

This is the autogenerate code after i run the command : php artisan make:auth After it generate the file and i set up for the database, it can let me to register and login. But it cant show the logout button after i login or register. The code above is checking the session have any user or not. If that is no user login, then it will come out the login and register button on the right of website. Like this:Default of the main page -

Main Page


But everything is remain same, and i could find out what is the wrong part.Auth::check() Auth::user() this two i already try, and it still didnt works. Anyone one have the solution?



via Chebli Mohamed

Passing additional variable to partial using @each in blade

from the documentation, only 4 parameters can be pass to @each. I don't think to use @include will help. here my code

@each('partials.nav.categories', $groupCategories, 'parent')

I need to send through an additional variable for use in the partial partials.nav.categories. This variable is not contained within the $groupCategories array.

Is there any way to send this additional variable through or do I have to append it to each item in the partials.nav.categories array?

Thanks



via Chebli Mohamed

mercredi 30 décembre 2015

Kill duplicate Sessions on Server in Laravel 5.2

What is it about ?

The database session driver now includes user_id and ip_address so you can easily clear all sessions for a given user.

What's the Problem

I checked this Article while reading what's new in Laravel 5.2

Is there any blog that clearly explains on how to logout the duplicate sessions created using multiple IP address or through the same IP address using multiple browsers ?



via Chebli Mohamed

Parse WHERE php

I using http://ift.tt/USpUaq. I want to send notify 2 other devices. But it's only send notify for device token is 'abcdef'. How to send notify 2 other devices? Thanks all,

    $query = ParseInstallation::query();
    $query->equalTo('deviceToken', 'xxxxx');
    $query->equalTo('deviceToken', 'abcdef');

    $data = [
        'data'  => ['alert' => 'Hello, this is a test'],
        'where' => $query,
        ];
    ParsePush::send(
        $data
    );



via Chebli Mohamed

Laravel - How to check reset password email sent successfully to the user?

I have following function postEmail in my PasswordController.php and calling when user trying to reset password.

/**
     * Send a reset link to the given user.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postEmail(Request $request)
    {
        //echo Input::get('ID'); die;
        $this->validate($request, ['ID' => 'required|email']);

        // Pass data to reset password mail template
        view()->composer('emails.password', function($view) {
            $view->with([
                'UserProduct1'   => 'UserProduct1',
                'UserProduct2'   => 'UserProduct2',
            ]);
        });

        $response = Password::sendResetLink($request->only('ID'), function (Message $message) {
            $message->subject($this->getEmailSubject());
        });

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

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

Is there any way to check, reset email sent or not to the user in laravel.

Any Idea?

Thanks.



via Chebli Mohamed

Scaffold Controller Laravel 5.2 Artisan

I am running following command:

php artisan make:controller UserController

This is successfully creating Controller but i want to scaffold it with all the basic methods. Can someone tell how i can do that. Thanks



via Chebli Mohamed

In Laravel, command function of Schedule class is not working

I am using Laravel 5 for my Project. I want to create a scheduler that will insert a user data in my database at every five minutes. I am using windows and I have created a windows scheduler task with a BAT file that will run in every minutes.

In laravel part, I added my codes in kernel.php, please take a look:

enter image description here

I also created a class in Commands folder named "InsertUser". Please take a look:

enter image description here

But it is not working, it always show "No scheduled commands are ready to run." message.

For your help, I want to add other information as well. In kernel.php, when I used call method instead of command it is working. Please take a look:

enter image description here

In CLI message:

enter image description here

Call function is working fine but Command function is not working. Please help me with your solid knowledge. Thanks.



via Chebli Mohamed

nginx with site in a subdir which does not match the ends of url

When I try to use laravel PHP framework, I try to place it in a dir called /home/usr/proj/laravel, but as we know that the public html of laravel is settled in /home/usr/proj/laravel/public, thus my problem is how to make the setting of nginx such that when I access by mysite.com/laravel/ or mysite.com/laravel, we in fact redirected to the location laravel/public/index.php.

Also, it seems that there is a rule of nignx which is suggested by the official of laravel, to make the url looks pretty

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

How can I use this in my case?



via Chebli Mohamed

Angular JS file upload with JSON

Im using the package below:

http://ift.tt/1B2mEGK

I can touch my file, but im running on the fact that my console.log gives back a blob. How can i transform that to an image? My console.log is here below:

File {$ngfBlobUrl: "blob:http%3A//http://ift.tt/22ziisg", $ngfWidth: 1200, $ngfHeight: 1600}
  $ngfBlobUrl: "blob:http%3A//http://ift.tt/22ziisg"
  $ngfHeight: 1600
  $ngfWidth: 1200
  lastModified: 1451421983000
  lastModifiedDate: Tue Dec 29 2015 21:46:23 GMT+0100 (CET)
  name: "20151229124600.jpg"
  size: 414563
  type: "image/jpeg"
  webkitRelativePath: ""
  __proto__: File

Currently i only have this in my EventController:

$scope.setFlyer = function ( part )
{
    console.log($scope.flyers.front);
    console.log($scope.flyers.front.$ngfBlobUrl);


    $scope.flyers[part] = {
        blob: $scope.flyers[part].$ngfBlobUrl
    };

};

$scope.updateEvent = function ()
{
    eventFactory.setEvent($scope.event.event, $scope.organisationID, $scope.flyers)
        .then(function ( response )
        {
            if ( response.data.status == 'success' )
            {
                eventFactory.getEvents(1, $scope.organisationID)
                    .then(function ( response )
                    {
                        $scope.events = response.data.events;
                        $scope.event = [];
                        $scope.event.club = [];
                        $scope.event.organisation = [];
                    });
            }
        });
};

My eventDirective:

setEvent: function ( data, organisationID, flyerSet )
    {
        var json = JSON.stringify({
            json: data,
            organisation_id: organisationID,
            flyers: flyerSet
        });

        return $http.post('/api/v1/event/update', json);
    }



via Chebli Mohamed

How can I set a session var using javascript and get it via php code

I have a javascript code like this :

<script type="text/javascript">

    $('#editRole').on('show.bs.modal', function (e) {  

        $roleID =  $(e.relatedTarget).attr('data-id');
        // Here I want to set this $roleID in session may be like this :
        Session['roleID'] = $roleID;                      
    });    

</script>

Then I want to get that $roleID in an other place using php code, may be like this :

<?php $roleID = Session::get('roleID'); //do something ....  ?>

Thanks



via Chebli Mohamed

Get Value in Deep Object/Array

I'm using the Twitter Api PHP library which returns the following object fine in my controller:

$tw_trends = $this->twitter->trends();

[
    {
        "trends": [
            {
                "name": "Bill Cosby",
                "url": "http://twitter.com/search?q=%22Bill+Cosby%22",
                "promoted_content": null,
                "query": "%22Bill+Cosby%22",
                "tweet_volume": 229907
            },
            ...

However, when I pass the $tw_trends to my view and try and do the following foreach, I get an error. How can I access the name value in the above object?

@foreach ($tw_trends as $trend)
    <ul>
        <li>
            {{ $trend->name }}
        </li>
    </ul>
@endforeach

Error:

Undefined property: stdClass::$name



via Chebli Mohamed

union query in laravel 5

My regular query is like this :

select "tb_news"."id" as "id", "tb_news"."title" as "title", "tb_news"."content" as "content" 
from "tb_news" 
where "tb_news"."id"  = 95
union 
select "tb_news_two"."id" as "id", "tb_news_two"."title" as "title", "tb_news_two"."content" as "content" 
from "tb_news_two"
where "tb_news_two"."id"  = 95 

I change the regular query to a query laravel.

My laravel query is like this :

$news_two = DB::table('tb_news_twor')->select('tb_news_two.id AS id','tb_news_two.title AS title ','tb_news_two.content AS content')
                                   ->where('tb_news_two.id',$news_id);
$news = DB::table('tb_news')->select('tb_news.id AS id','ss_msnews.title AS title ','tb_news.content AS content')
                                 ->union($news_two)
                                 ->where('tb_news.id',$news_id);

But, My laravel query not working.

How do I use the unions in laravel with where ?

Thank you



via Chebli Mohamed

Laravel - Connection could not be established with host smtp.gmail.com

I'm trying to send an email using the standard email feature in Laravel 5.

I'm using smtp from google to send mails. When working local the email sends without a problem. But when I'm trying to do the same on my hosting (one.com) I get the following error.

Swift_TransportException in StreamBuffer.php line 265:
Connection could not be established with host smtp.gmail.com [Connection timed out #110]
in StreamBuffer.php line 265
at Swift_Transport_StreamBuffer->_establishSocketConnection() in StreamBuffer.php line 62
at Swift_Transport_StreamBuffer->initialize(array('protocol' => 'tcp', 'host' => 'smtp.gmail.com', 'port' => '587', 'timeout' => '30', 'blocking' => '1', 'tls'     => true, 'type' => '1')) in AbstractSmtpTransport.php line 113
at Swift_Transport_AbstractSmtpTransport->start() in Mailer.php line 79



via Chebli Mohamed

Laravel returns htmlentities() expects parameter 1 to be string, object given

I have the following Laravel 5.1 controller function

public function editare($prod_id) {

    $categorii=DB::table('categorii_produse')
        ->select('cat_id')
        ->get();

    $categorie_selectata=DB::table('produse')
        ->leftjoin('categorii_produse','prod_cat_id','=','cat_id')
        ->where('prod_id','=',$prod_id)
        ->select('prod_cat_id')
        ->get();

    $articole=DB::table('produse')
        ->leftjoin('imagini','prod_id','=','img_prod_id')
        ->where('prod_id','=',$prod_id)
        ->get();


    return view ('pagini.editare',compact('categorii','categorie_selectata','articole'));

And the following line in the view which has problems

{!! Form::select('categorii',$categorii, null, ['class' => 'form-control']) !!}

The view returns the following error

htmlentities() expects parameter 1 to be string, object given



via Chebli Mohamed

laravel wont work with $ ? in the url

i have offers api from a website and this return this url

http://mylaravelsite/offers/done/?id=100&oid=12&o_name=YurMobile-FI&amount=10cy_name=Qoins&user_id=1&sig=606a5e547ed5c607b10f97a5958f4c38&payout=5.250

i used this routing code

Route::get('/offers/data/{data}', "HomeController@offersdone");

but the url showed every time

NotFoundHttpException in RouteCollection.php line 161:

What do i wrong or is missing ?



via Chebli Mohamed

How to force Restangular's getList to work with Laravel 5's pagination object?

I have a page where I want to display user's posts paginated. For back-end I use Laravel's resource controllers and on the front-end Restangular services.

So back-end implementation looks like this:

// url is /users/0/posts
public function index(Post $post)
{
    return $post->whereUserId(\Auth::id())->paginate(20);
}

Front-end looks like this:

/*
 * posts.service.js
 */
angular.module('app.services')
    .service('posts', Posts);

Posts.$inject = ['Restangular'];

function Posts(Restangular) {
    return Restangular.service('posts', Restangular.one('users', 0));
}



/*
 * posts.controller.js
 */
angular.module('koodzo.controllers')
    .controller('PostsController', PostsController);

ContentController.$inject = ['posts'];

function PostController(posts) {
    var vm = this;

    vm.posts = posts.getList()
        .then(function(response) {
            vm.pagination = response;
            vm.posts = response.data;
        });
}

So, obviously, this doesn't work, because Restangular's getList expects to receive an array from the server to restangularize it, but Laravel's paginator returns an object and the array is in the data field of the object.

The question is how to make Restangular see that response.data is the array that it needs?



via Chebli Mohamed

How to represent an ordered recursive relationship in Laravel?

Schema

I have the following database schema:

=== modules ===
id: PK
name: String
current_revision: FK to revisions.id

=== revisions ===
id: PK
module_id: unsigned int, indexed, FK to modules.id
parent_revision: unsigned int, nullable, indexed, FK to revisions.id
content: string

Example Data

Example data

modules:

(1, "Maths, 3)
(2, "Computing", 5)

revisions:

(1, 1, null, "Maths - v1")
(2, 1, 1, "Maths- v2")
(3, 1, 2, "Maths - v3")
(4, 2, null, "Computing - v1")
(5, 2, 4, "Computing - v2")

Explanation

As you can see, the parent_revision relates to the previous version of that module or null if it's the first version for the module.

The current_revision relates to the latest version for the category

What I want?

I wish to represent this relationship as a model in Laravel. I managed to make a start:

class Module extends Model
{
    public function currentRevision()
    {
        return $this->belongsTo(Revision::class, 'current_revision_id');
    }

    public function revisions()
    {
       /* Help! (I wish to return all the revisions for this module in
       order, starting from the current_revision. e.g. for the "Maths" 
       module it 
       should return the revisions with IDs: [3, 2, 1] and for the 
       "Computing" module it should return: [4, 3] )*/
    }
}

-

class Revision extends Model
{
    public function module()
    {
        return $this->belongsTo(Module::class);
    }

    public function nextRevision()
    {
        return $this->hasOne(Revision::class, 'parent_revision');
    }

    public function previousRevision()
    {
        return $this->belongsTo(Revision::class, 'parent_revision');
    }

    public function previousRevisions()
    {
        // TODO: return ALL previous revisions
    }
}

I wish to find an efficient way to create the revisions() method for the Module model. How can I do this?

NOTE: I don't mind if you suggest schema changes, provided it is better than what I have currently!



via Chebli Mohamed

Laravel Redirection doesn't work

I am using Laravel 5.1. My controller is specifically for admin users. So I check whether user is admin or not.This is my code.

public function getAdminData()
  {
    $this->checkAdminStatus();
    return response()->json(array('admin-data'));
  }
public function checkAdminStatus()
  {
    $userManager = new UserManager();
    if(!$userManager->isAdmin())
    {
        return redirect()->route('returnForbiddenAccess');
    }
  }

My route is

Route::any('api/app/forbidden',['uses' =>'ErrorController@returnNonAdminErrorStatus','as'=>'returnForbiddenAccess']);

Now if user is not admin, then it should not return admin-data yet it returns. Shouldn't it stop processing logic after redirect()->route call? Also this is purely REST application.



via Chebli Mohamed

Laravel does not recognize trait

I'm changing AuthenticatesUsers.php to use google recaptcha in postLogin method.

Have a trait

<?php

namespace App\Traits;

use Illuminate\Support\Facades\Input;
use ReCaptcha\ReCaptcha;

trait CaptchaTrait {
    public function captchaCheck()
    {
        ...
    }
}

and my AuthenticatesUsers.php starts with

<?php

namespace Illuminate\Foundation\Auth;

use App\Traits\CaptchaTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Lang;

trait AuthenticatesUsers
{
    use RedirectsUsers;
    use CaptchaTrait;
...
}

In login page, I get this error

FatalErrorException in AuthenticatesUsers.php line 13: Trait
'App\Traits\CaptchaTrait' not found

Can't understand why. In PhpStorm when importing class CaptchaTrait it automatically import App\Traits\CaptchaTrait to AuthenticatesUsers.php

What am I missing?



via Chebli Mohamed

Laralvel 5: Model object could call Builder method. How does Laravel do that?

In the Laravel package, the model User is derived from Model class. Although Model class does not have "join" method, I could still use join method on the user object.

I am not clear how does Laravel do that.

$user = Users::find($id);
$user->
    join('GroupMember', 'GroupMember.UserID', '=', 'users.id')->
    join('Groups', 'GroupMember.GroupID', '=', 'Groups.GroupID')->
    where('users.id','=', $user->id)->get();

The above code is to get all related groups of the user. Because the $user is derived from Model class, but the Model class dos not have "join" method...

Here is the User definition.

<?php namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;


class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

    use Authenticatable, CanResetPassword;



via Chebli Mohamed

Laravel - How to pass variable to reset password template?

I have implemented reset password functionality with Laravel 5 and getting email. Now how to pass some variable data to my email template to display more information about user.

/**
 * Send a reset link to the given user.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function postEmail(Request $request)
{
    //echo Input::get('ID'); die;
    $this->validate($request, ['ID' => 'required|email']);

    $UserProduct = "Sample 1"; // I want to pass this variable to my password.blade.php
    $response = Password::sendResetLink($request->only('ID'), function (Message $message) {
        $message->subject($this->getEmailSubject());
    });

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

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

}

I want to print $UserProduct = "Sample 1"; to my email template but don't know how to pass to the password.blade page.

Any idea?

Thanks.



via Chebli Mohamed

get related model without loop query

tables:

products:

id | name | author_id    

authors:

id | name

models:

product:

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

Then I get products:

$products = Product::where('name','like','username%')->get();
foreach ($products as $product) {
    $product->author;
}

Is there any way to get products with author without loop?



via Chebli Mohamed

How to fix in laravel 5.2 zizaco entrust:migration class name validation?

I have followed zizac/entrust installation tutorial from GitHub Link and faced with error:

Class name must be a valid object or a string in var/www/html/laravel_test/vendor/zizaco/entrust/src/commands/MigrationCommand.php on line 86

MigrationCommand.php file url : Link

Outut:

php artisan entrust:migration

Tables: roles, role_user, permissions, permission_role
A migration that creates 'roles', 'role_user', 'permissions', 'permission_role' tables will be created in database/migrations directory

Proceed with the migration creation? [Yes|no] (yes/no) [yes]: yes

Creating migration...
PHP Fatal error:  Class name must be a valid object or a string in /var/www/html/laravel_test/vendor/zizaco/entrust/src/commands/MigrationCommand.php on line 86

the command: php artisan vendor:publish was successful.

File : config/entrust.php exist.

I didin't change any options to config/auth.php file same as - auth.php. How to fix it?



via Chebli Mohamed

Laravel 5.2 login session not persisting

I have been implementing a simple authentication system on Laravel 5.2 using Sentinel.

// Route : /login
$success = Sentinel::authenticate(array(
   'email'    => $email,
   'password' => $password,
));

echo $success ? 'Login success' : 'Login failed';

So, the above code outputs Login success after the authentication code. But, the login status is not getting persisted to other requests. ie: if I check the authentication status from other requests, it is saying that I am not logged in!

// Route : test-login
echo \Sentinel::check() ? 'User is logged in' : 'User is not logged in';

I have even tried to implement a defaut laravel authencation using \Auth::attempt. But, that also giving the same thing.

Any help on this is greatly appreciated.



via Chebli Mohamed

get sum of all entries by column in laravel

So I have table prices with structure:

+----+--------+
| id | reward |
+----+--------+
| 1  | 721    |
+----+--------+
| 2  | 54     |
+----+--------+
| 3  | 99     |
+----+--------+

and I'm using this method to sum all rewards:

'withdrawals' => \App\Tradeoffer::where('type', 'withdraw')
            ->where('completed', 1)
            ->where('declined', 0)
            ->where('timeout', 0)
            ->where('created_at', '>', (time() - $hours))
            ->sum('reward')

and the response is: 7215499 instead of sum of all entries. Why is that? How to deal with it?



via Chebli Mohamed

Add items to query result - Laravel

I'm slowly moving my API to Laravel and coming to grips with the Query Builder.

I'm trying to achieve this:

$data = array();

$query = "SELECT * FROM blog_posts WHERE post_type = 3 AND post_status = 1  ORDER BY id DESC";
$result = mysqli_query($cms_connection, $query);
if($result) {
    while($row = mysqli_fetch_assoc($result)) {
        $row['post_seo'] = seoUrl($row['post_title']);
        $data['data'][] = $row;
    }
    $data['success'] = true;
    $response = json_encode($data);
}

My problem isn't necessarily with getting the query, but as you can see I'm using the result of the query and then injecting it back into the final array.

So essentially, I'm fetching rows, transforming some of the attributes fetched, and then injecting the newly created attributes into the resulting array.

This is what I have so far:

$posts = DB::table('blog_posts')
    -where(['post_type' => 1, 'post_status' => 1)
    ->orderBy('id', 'desc')
    ->take(5)->get();



via Chebli Mohamed

Laravel 4 - Controller method not found

I want to modify an user from the list. I have the codes in the routes.php:

Route::get('users/{all}/edit', 'UserController@getEdit');
Route::post('users/update', ['as' => 'users.postUpdate', 'uses' => 'UserController@postUpdate']);
Route::controller('users', 'UserController');

In the UserController.php, I wrote the following script for edit and update:

public function getEdit($id)
{
    //

    $user = User::find($id);
    if (is_null($user))
        {

            return Redirect::to('users/all');
        }
    return View::make('users.edit', compact('user'));
}


/**
 * Update the specified resource in storage.
 *
 * @param  int  $id
 * @return Response
 */
public function postUpdate($id)
{
    //


    $input = Input::all();
    $validation = Validator::make($input, User::$rules);
    if ($validation->passes())
    {
        //$user = User::find($id);

            $user = User::find($id);
            $user->username = Input::get('username');
            $user->name = Input::get('name');
            $user->email = Input::get('email');
            $user->phone = Input::get('phone');
            $user->password = Hash::make(Input::get('password'));
            $user->save();

        return Redirect::route('users.getIndex', $id);
    }
    return Redirect::route('users.getEdit', $id)
        ->withInput()
        ->withErrors($validation)
        ->with('message', 'There were validation errors.');
}

The code under edit.blade.php as below:

@extends('users.user') 

@section('main')

<h1>Edit User</h1>
{{ Form::model($user, array('method' => 'PATCH', 'route' => array('users.postUpdate', $user->id))) }}
<ul>
    <li>
        {{ Form::label('username', 'Username:') }}
        {{ Form::text('username') }}
    </li>
    <li>
        {{ Form::label('password', 'Password:') }}
        {{ Form::text('password') }}
    </li>
    <li>
        {{ Form::label('email', 'Email:') }}
        {{ Form::text('email') }}
    </li>
    <li>
        {{ Form::label('phone', 'Phone:') }}
        {{ Form::text('phone') }}
    </li>
    <li>
        {{ Form::label('name', 'Name:') }}
        {{ Form::text('name') }}
    </li>
    <li>
        {{ Form::submit('Update', array('class' => 'btn btn-info')) }}
        {{ link_to_route('users.getAll', 'Cancel', $user->id, array('class' => 'btn')) }}
    </li>
</ul>
{{ Form::close() }}

@if ($errors->any())
<ul>
    {{ implode('', $errors->all('<li class="error">:message</li>')) }}
</ul>
@endif

@stop

The edit screen is opening well. However, when modify the values and submit the form, the URL shows as http://localhost/testlaravell/users/update?5 and the error occurs that -

Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException
Controller method not found.

Please help me how can I solve this issue.



via Chebli Mohamed

Why does a Laravel resource controller limited to update generate two routes?

Given the following defined route in routes.php:

Route::resource('smoker','SmokerController',['only' => ['update']]);

..results in the generation of two distinct routes:

| PUT   | profile/smoker/{smoker}| profile.smoker.update | App\Http\Controllers\Profile\SmokerController@update |
| PATCH | profile/smoker/{smoker}|                       | App\Http\Controllers\Profile\SmokerController@update |

I can hazard a guess that both PUT and PATCH verbs are close enough in a restful environment that they both fall under an 'update' restriction. I can't find any documentation to support that guess, nor can I find anywhere documentation why one (PUT) has it's alias automatically set, in this case, to profile.smoker.update.

What is more confusing, is that a similar restriction, 'show', results in a verbs GET and HEAD being merged as GET|HEAD in the route list.

| GET|HEAD | profile/smoker/{smoker}| profile.smoker.show | App\Http\Controllers\Profile\SmokerController@show |

Why is GET and HEAD merged, but PUT and PATCH not?



via Chebli Mohamed

How to mock Cache::remember in Laravel

Within a unit test method, I tried to mock a Cache::remember response like this:

Cache::shouldReceive('remember')
    ->once()
    ->with('my_key', 120, function() {}) // There are 3 args in remember method
    ->andReturn([]);

But I get this error:

exception 'Mockery\Exception\NoMatchingExpectationException' with message 'No matching handler found for Mockery_0_Illuminate_Cache_CacheManager::remember ("my_key", 120, object(Closure)). Either the method was unexpected or its arguments matched no expected argument list for this method

I don't understand why I got this error and did not found anything in Laravel documentation about this. It says there is no matching, but it seems to match.

How can I mock a mock a Cache::remember response?



via Chebli Mohamed

RestFul API design and Session management - Laravel

So this is a general question that I have with regards to RESTFul API architecture.

I'm using Laravel.

I want all users of my website to be able to login/signup to the Website(not the API, I'm not trying to authenticate the origin) through an API. Illustration below

Client --> Web server --> API server

So normal design is that your php login/logout/signup scripts are on your Web server and when a user tries to login, script goes to DB to validate, and then you set a session on the web server and pass a cookie to the client if they are validate. Now the web server has a reference to that cookie and anytime the same client comes back web server recognises them. Same way if they logout, the cookie reference on the web server is destroyed.

Now in my illustration, the API server will see the web server as a client if the login/logout/signup scripts are on it. So the API server will create a session and pass the cookie to the web server. The web server tells the client they have been validated but will not pass the cookie to it.

So user is client to web server but web server is client to API server.

  1. Is my understanding correct?
  2. Can this architecture be done?


via Chebli Mohamed

Laravel: Form Data binding

Scenario:

I have a form for each subject and each subject have three or four questions and the user have to answer those question then save the data on the database

The problem:

How to bind the data with the form so the form refilled with the data that inputted before by the user. I have tried a lot and search a lot to find a solution but I didn't find anything useful.

Code:

Controller:

public function saveData(Request $request, $user_id, $subject_id)
    {
        $all_data = $request->input('row');
        foreach ($all_data as $data) {
            $question_id = $data['question_id'];
            $check_data = ['user_id' => $user_id, 'question_id' => $question_id, 'subject_id' => $subject_id];
            $exist_data = RatingDatum::where($check_data)->get()->first();
            if (is_null($exist_data)) {
                RatingDatum::create($data);
            } else {
                $save = RatingDatum::findorfail($exist_data->id);
                $save->update($data);
            }
        }
        flash()->success('Data has been submitted.');
        return 'done';
    }

View :

   <div class="row">
                {!! Form::model(['method' => 'PATCH','action'=>['RatingDataController@saveData'],$organisation->id,$organisation->sector->id]) !!}
           <div class=" col-md-9">
                            <h3> {{$subject_name->subject}}</h3>
                            @foreach($question as $index=>$question)
                                <div class="plan bg-plan">
                                    <h5>{{$question->question}}</h5>
                                    <hr>
                                    <!-- create sector form -->
                                    @foreach($answers as $answer)
                                            <div class="radio">
                                                <label> 
                             {!! Form::radio('row['.$index.'][answer_id]', $answer->id,true)!!}                                                        
                                                  {{$answer->answer}}
                                                </label>

                                            </div>
                                    @endforeach
                                    <div class="form-group">
                                        {!! Form::label('comment','Comment :') !!}
                                        {!! Form::textarea('row['.$index.'][comment]' ,null,['class'=>'form-control', 'rows' => 4]) !!}
                                    </div>                             
                                </div>
                            @endforeach
                        </div>
                        {!! Form::submit('Submit Data', ['class' => 'btn btn-success submit right']) !!}

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



via Chebli Mohamed

print on shown table using pdf-laravel

currently, I am using a library of pdf-laravel to display the data in pdf file. it was working when I wrote data directly in the new page to be shown. here, I got the problem on how to display the selected data to be printed. below is my report.blade.php.

<table class=" table-autosort table-autofilter " border="1" width="100%">
       <thead>
            <tr><br>
                <td>bil</td>
                <td class="table-filterable table-sortable:numeric table-sortable"> faculty</td>
                <td class="table-filterable table-sortable:numeric table-sortable"> programme</td>
             </tr>

        </thead>
        <tbody class="bottom-right" >

                 @foreach($profiles as $profile)
               <tr>
                   <!--<td class="student_id" width="15%">{{$profile->student_id }}</td>
                    <td class="name" width="30%">{{$profile->student_name }}</td>-->
                    <td class="number" width="7%%"></td>
                    <td class="faculty" width="40%">{{$profile->faculty }} </td>
                    <td class="program" width="53%%"> {{$profile->program }}</td>
                 </tr>
               @endforeach
         </tbody>
    </table>

      <br><p align="right"><a href="{{ url('print/') }}"  target="_blank">Print</a></p>
        </fieldset>
   </div>

what should I do when I click the print button(just one print button ), it will print any data of current table has shown (either filter: all ; or filter: program ) ?



via Chebli Mohamed

Laravel 5.1 Session and Socket.IO + Redis - Sending Notifications to Logged In (Known) Users and Group Of Users

I am working on a project where I want to implement real-time notifications for a specific group of users (with role of Admin) and after some research, I understood that I'll need the session in order to know which users are logged in (by default they are anonymous).

Also, I'll need to implement notifications to specific users only. (only one user, example: John Doe)

So, my questions are:

  1. How can I transfer the session/cookie over to the NodeJS side through Redis and then emit the notification?

  2. What should I do exactly?

  3. Any encryption / decryption?

Anyone ever had any chance to implement anything like this?

There's almost no info about this on the internet and most of the tutorials are way too basic for my use case.

I am using Laravel 5.1 Broadcasting features to publish some notifications and display them in real-time with Socket.io (version 1.3.7). I also use Redis (version 3), NodeJS (version 5) and Express (version 4.13).

Thanks for reading!



via Chebli Mohamed

Editing drop-down doesn't fetch value

I have created a drop-down for categories and subcategory. It works fine when i submit the form, but when I edit the form, category field does not come with refilled data from the database, category drop-down come like it show in create form.

here is my edit:

    <div class="form-group">
    {!! Form::label('category','Category:') !!}
    <select name="category" id="category" class="form-control input-sm">
        @foreach($s as $k)
            <option value="{{ $k['id'] }}">{{ $k['name'] }}</option>
        @endforeach
    </select>
</div>

<div class="form-group">
    {!! Form::label('subcategory','Subcategory:') !!}
    <select name="subcategory" id="subcategory" class="form-control input-sm">
        <option value=""></option>
    </select>
</div>

Controller:

    public function edit($id)
{
    // get the event
    $event = Event::findOrFail($id);
    $s = Category::all()->where('parent_id','=','0');
    $r = Event::all();
    $daysOfWeek = unserialize(Event::find($id)->days_of_week);
    // show the edit form and pass the event
    return view('event.edit',compact('event','s','r','daysOfWeek'));}

I haven't used relations for the dropdown, I have used jquery and ajax to select subcategory after I select category. What can i do to get the value stored in database when I do edit form?



via Chebli Mohamed

mardi 29 décembre 2015

How to handle sessions in Laravel 5 with the Parse SDK?

I'm building an app using the Parse PHP SDK in Laravel 5 (I use "Laravel-Parse" by Graham Campbell for the Parse SDK integration).

I am able to create a user with this code :

$user = new ParseUser();
$user->setUsername($username);
$user->setEmail($email);
$user->setPassword($password);

try {
    $user->signUp();
} catch (ParseException $ex) {
    // error in $ex->getMessage();
}

... then I can log-in :

try {
    $user = ParseUser::logIn($username, $password);
} catch(ParseException $ex) {
    // error in $ex->getMessage();
}

and just after this code, I can get the current user from Parse :

$user = ParseUser::getCurrentUser();

The "getCurrentUser()" function returns the current user if I execute this code just after the Parse login function. However, if I go to another page in my Laravel website, and try to get the current user again with the same code, I get an empty array.

I guess it is a session error, can you tell me if I missed anything ? Or how to fix that ?

Thanks.



via Chebli Mohamed

Error in defining Multi Auth variable in constructor in laravel

When I define user name in constructor then In composer when I run route:list Command then I find error

Code:

public function __construct()

{
    $this->data = [];
    $this->data['pageTitle'] = 'Category';
    $this->data['username'] =  Auth::admin()->get()->email;
    $this->data['categories'] = Category::all();
}

Error :

http://ift.tt/22xTvot

But When I define username in functions like in index or show function then it work properly but I want to define this 'Auth' variable in constructor so that I can use this variable in whole controller's function so that I don't have any need to define in different different function .

Code:

Here

public function __construct() {

    $this->data = [];
    $this->data['pageTitle'] = 'Category';
    $this->data['categories'] = Category::all();
}

/**
 * Display a listing of the resource.
 *
 * @return Response
 */
public function index()
{
    $this->data['username'] =  Auth::admin()->get()->email;
    return view('admin.category.index',$this->data);

}



via Chebli Mohamed

Route protection - Laravel

So I have a route with 3 parameters like so

Route::get('search-restaurant/{location}/{day}/{time}', 'WebController@search_restaurant');

For every request to this route, I want to verify these parameters in some way or another.

For the time parameter I've seen documentation of how to attach a regex to it but no documentation in 5.2 but even if I found the docs I need to verify others as well

So basically I have tried two different ways to check and verify the parameters but none are working.

Method 1 - Conroller

public function search_restaurant ($location, $day, $time) {

    if($day != 'today' || $day != 'tomorrow') {
        abort(500);
    } elseif (!in_array($location, $locations)) {
        abort(500);
    } elseif (!preg_match("/(2[0-3]|[01][0-9])([0-5][0-9])/", $time) && $time != "asap") {
        abort(500);
    } elseif ($day == "tomorrow" && $time == "asap") {
        abort(500);
    } else {
    .....//rest of code - send to view
    }
}

Method 2 - Middleware

public function handle($request, Closure $next)
{

    $location = $request->route('location');
    $day = $request->route('day');
    $time = $request->route('time');

    $locations = Array('central','garki-1','garki-2','wuse-2','wuse-1','gwarimpa','maitama','asokoro');

    if($day != 'today' || $day != 'tomorrow') { // check string
        abort(500);
    } elseif (!in_array($location, $locations)) { // check against array
        abort(500);
    } elseif (!preg_match("/(2[0-3]|[01][0-9])([0-5][0-9])/", $time) && $time != "asap") { // check agains regex
        abort(500);
    } elseif ($day == "tomorrow" && $time == "asap") { // check against string
        abort(500);
    }

    return $next($request);
}

As you can see I'm simple doing simple if..else statements on the variables but the conditions seem to always be true. I have tried these rules one by one also but every time they fail and I get sent to 500 page.

Any guidance appreciated



via Chebli Mohamed

Get extension file in Laravel 5

My code in view is like this :

@foreach($news as $row)
    <div class="dealprice">
        <p class="size8 red lh2">File Path: {{ $row->file_path}}</p>
    </div>                  
@endforeach

The result of {{ $row->file_path}} : assets/images/Test.pdf

I want the result : pdf

How do I get the file extension?

Thank you



via Chebli Mohamed

Can't access Laravel helper class from a view

I have my Helper file located at app/Helpers/Helper.php

class Helper {

    // Add body class
    public static function bodyClass() {
        $body_classes = array();
        $class = "";

        foreach ( \Request::segments() as $segment ) {
            if ( is_numeric( $segment ) || empty( $segment ) ) {
            continue;
            }

            $class .= ! empty( $class ) ? "-" . $segment : $segment;
            array_push( $body_classes, $class );
        }
        return ! empty( $body_classes ) ? implode( ' ', $body_classes ) : NULL;
    }
}

Then in my composer.json, I autoloaded this Helper file like this:

"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/Helpers/Helper.php"
    ]
},

Then in one of my master views, I have this:

<body class="{{ Helper::bodyClass() }}">

But I get an error saying:

Class 'Helper' not found

I also did dump autoload so that shouldn't be the issue. Anyone have any clues?

Thanks!



via Chebli Mohamed

failed to download pdf in laravel 5

My code is like this :

<a href="javascript:;" onclick="showAjaxPdf('{{ $row->file_path }}');"><i class="fa fa-file-pdf-o"></i></a>

My javascript code is like this :

  function showAjaxPdf(file_path){
//example : file_path = assets/images/myfile.pdf
                $.post("news/test", { file_path: file_path } ); 
            }

My function test in controller :

 public function postTest(Request $request)
        {  
$file_path = $request->input('file_path');
            return response()->download($file_path);       
        }

When I click on the pdf icon, no response

I wish, when click on the pdf icon, appear like this: enter image description here

Thank you



via Chebli Mohamed

Functions in controllers and blade - Laravel

Ce résumé n'est pas disponible. Veuillez cliquer ici pour afficher l'article.

failed to send parameter from javascript to controller in laravel 5

My code is like this :

<a href="javascript:;" onclick="showAjaxPdf('{{ $row->file_path }}');"><i class="fa fa-file-pdf-o"></i></a>

My javascript code is like this :

  function showAjaxPdf(file_path){
//example : file_path = assets/images/myfile.pdf
                $.post("news/test", { name: file_path } ); 
            }

My function test in controller :

public function postTest($file_path)
    {  
        return response()->download($file_path);       
    }

When I click on the pdf icon, failed to send parameter from javascript to controller

I wish, when click on the pdf icon, appear like this: http://ift.tt/1IChlsz

Thank you



via Chebli Mohamed

Php artisan not working (laravel 5.1)

Suddenly when i type php artisan or any artisan command i seen this message

[ErrorException]
Trying to get property of non-object

I tried the following

1- php artisan clear-compiled

2- To delete vendor directory and use composer install Or composer update

3- clone a standard Laravel app and put my files app dir and my config and use composer commands but with step the error has changed to be

[ErrorException]
Trying to get property of non-object

Script php artisan clear-compiled handling the post-install-cmd event returned with an error

[RuntimeException]
Error Output:

Any Suggestions ?

Thanks



via Chebli Mohamed

Laravel: How to bind form data

Scenario:

I have a form for each subject and each subject have three or four questions and the user have to answer those question then save the data on the database

The problem:

How to bind the data with the form so the form refilled with the data that inputted before by the user. I have tried a lot and search a lot to find a solution but I didn't find anything useful.

Code: View :

   <div class="row">
                {!! Form::model(['method' => 'PATCH','action'=>['RatingDataController@saveData'],$organisation->id,$organisation->sector->id]) !!}
           <div class=" col-md-9">
                            <h3> {{$subject_name->subject}}</h3>
                            @foreach($question as $index=>$question)
                                <div class="plan bg-plan">
                                    <h5>{{$question->question}}</h5>
                                    <hr>
                                    <!-- create sector form -->
                                    @foreach($answers as $answer)
                                            <div class="radio">
                                                <label> 
                             {!! Form::radio('row['.$index.'][answer_id]', $answer->id,true)!!}                                                        
                                                  {{$answer->answer}}
                                                </label>

                                            </div>
                                    @endforeach
                                    <div class="form-group">
                                        {!! Form::label('comment','Comment :') !!}
                                        {!! Form::textarea('row['.$index.'][comment]' ,null,['class'=>'form-control', 'rows' => 4]) !!}
                                    </div>                             
                                </div>
                            @endforeach
                        </div>
                        {!! Form::submit('Submit Data', ['class' => 'btn btn-success submit right']) !!}

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



via Chebli Mohamed

Correct way to handle CSV Files on PHP

Hi I have the following brain braking thing going on. The thig is that I'm developing a Laravel Application that imports and exports CSV files. Now, the data that the application Imports/Exports(I/E now on) has fields from various data types, we have text and numbers, now the text can contain commas(,) and using the default CSV separator (,) on php can lead to fields on the import to generate incorrectly. The client suggested that I I/E using ^ as a separator for the export and (,) again for the import of the data. Now, my question is, can I trust when I/E data using the default separator? Can anyone suggest a best way to do the I/E process?

Edit The client main struggle is because he uses Excel on a Mac to edit the CSV files, now on my Mac, I can easily edit the files without any issues regarding the separator, of course if the separator is a comma (,) but if we use the ^ as a separator then my excel is a mess and he's ommit some fields.

Thanks in advance.



via Chebli Mohamed

response ajax download pdf (laravel 5)

My html code is like this :

<a href="javascript:;" onclick="showAjaxPdf('{{ $row->file_path }}');"><i class="fa fa-file-pdf-o"></i></a>

My javascript code is like this :

function showAjaxPdf(file_path)
        {
            var file_path = file_path.replace(/\\/g,"/");
            //example : file_path = assets/images/myfile.pdf
            $.ajax({
                type: "POST",
                data: 'file_path=' + file_path,
                url: "news/test",
                success: function(response)
                {
                    $('#test').html(response);

                }
            });
        }

My function test in controller :

public function postTest(Request $request)
    {
$file_path = $request->input('file_path');  
        return response()->download($file_path);       
    }

When I click on the pdf icon, no response.

I wish, when click on the pdf icon, appear like this:

enter image description here

how to keep the current click pdf icon, the image appears like it?

Thank you



via Chebli Mohamed

Simplest way to use Mail::queue with Laravel 5, IronMQ?

I've read other posts on StackOverflow and elsewhere on using Laravel mail and IronMQ, e.g. Using Mail::queue with iron.io - they either advocate using Queue::push and Mail::send together, or else say you can use Mail::queue but don't provide specific examples of code.

Is it possible to queue emails with just Mail::queue? (i.e. without using Queue::push?)

I've tried with the code below, but Mail::queue here doesn't actually send a message to Iron (my other settings should be OK as I can see Queue::push works, and Mail::send works too just without the queue getting involved)

public function submit_contact_form()
{
        ContactForm::create(['email'=>$_POST['email'],'query'=>$_POST['query'],'name'=>$_POST['name']]);
   $name_fixed = ucwords(strtolower($_POST['name']));
 $data = array('name'=>$name_fixed, 'query'=>$_POST['query']);
    Mail::queue('emails.contact_form', $data, function($message) {
        $name_fixed = ucwords(strtolower($_POST['name']));
        $message->to($_POST['email'], $name_fixed)->subject('Contact received');
    });

}


Route::post('/queue',  function() {
return Queue::marshal();
});

So to sum up, what's the simplest / most efficient way to use Iron queues with Laravel 5 mail?

Thanks



via Chebli Mohamed

Cannot install global homestead: Your requirements could not be resolved

I am trying to install homestead on OSX 10.11. I want to be up and running building laravel applications. I cannot run homestead from the command line. When I try to install it globally I get an error:

$ composer global require "laravel/homestead=~2.0"
Changed current directory to /Users/connorleech/.composer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: don't install laravel/homestead v2.1.8
    - Conclusion: don't install laravel/homestead v2.1.7
    - Conclusion: don't install laravel/homestead v2.1.6
    - Conclusion: don't install laravel/homestead v2.1.5
    - Conclusion: don't install laravel/homestead v2.1.4
    - Conclusion: don't install laravel/homestead v2.1.3
    - Conclusion: don't install laravel/homestead v2.1.2
    - Conclusion: don't install laravel/homestead v2.1.1
    - Conclusion: don't install laravel/homestead v2.1.0
    - Conclusion: don't install laravel/homestead v2.0.17
    - Conclusion: don't install laravel/homestead v2.0.16
    - Conclusion: don't install laravel/homestead v2.0.15
    - Conclusion: don't install laravel/homestead v2.0.14
    - Conclusion: don't install laravel/homestead v2.0.13
    - Conclusion: don't install laravel/homestead v2.0.12
    - Conclusion: don't install laravel/homestead v2.0.11
    - Conclusion: don't install laravel/homestead v2.0.10
    - Conclusion: don't install laravel/homestead v2.0.9
    - Conclusion: don't install laravel/homestead v2.0.8
    - Conclusion: don't install laravel/homestead v2.0.7
    - Conclusion: don't install laravel/homestead v2.0.6
    - Conclusion: don't install laravel/homestead v2.0.5
    - Conclusion: don't install laravel/homestead v2.0.4
    - Conclusion: don't install laravel/homestead v2.0.3
    - Conclusion: don't install laravel/homestead v2.0.2
    - Conclusion: don't install laravel/homestead v2.0.1
    - Conclusion: remove symfony/console v3.0.1
    - Installation request for laravel/homestead ~2.0 -> satisfiable by laravel/homestead[v2.0.0, v2.0.1, v2.0.10, v2.0.11, v2.0.12, v2.0.13, v2.0.14, v2.0.15, v2.0.16, v2.0.17, v2.0.2, v2.0.3, v2.0.4, v2.0.5, v2.0.6, v2.0.7, v2.0.8, v2.0.9, v2.1.0, v2.1.1, v2.1.2, v2.1.3, v2.1.4, v2.1.5, v2.1.6, v2.1.7, v2.1.8].
    - Conclusion: don't install symfony/console v3.0.1
    - laravel/homestead v2.0.0 requires symfony/console ~2.0 -> satisfiable by symfony/console[2.0.4, 2.0.5, 2.0.6, 2.0.7, v2.0.10, v2.0.12, v2.0.13, v2.0.14, v2.0.15, v2.0.16, v2.0.17, v2.0.18, v2.0.19, v2.0.20, v2.0.21, v2.0.22, v2.0.23, v2.0.24, v2.0.25, v2.0.9, v2.1.0, v2.1.1, v2.1.10, v2.1.11, v2.1.12, v2.1.13, v2.1.2, v2.1.3, v2.1.4, v2.1.5, v2.1.6, v2.1.7, v2.1.8, v2.1.9, v2.2.0, v2.2.1, v2.2.10, v2.2.11, v2.2.2, v2.2.3, v2.2.4, v2.2.5, v2.2.6, v2.2.7, v2.2.8, v2.2.9, v2.3.0, v2.3.1, v2.3.10, v2.3.11, v2.3.12, v2.3.13, v2.3.14, v2.3.15, v2.3.16, v2.3.17, v2.3.18, v2.3.19, v2.3.2, v2.3.20, v2.3.21, v2.3.22, v2.3.23, v2.3.24, v2.3.25, v2.3.26, v2.3.27, v2.3.28, v2.3.29, v2.3.3, v2.3.30, v2.3.31, v2.3.32, v2.3.33, v2.3.34, v2.3.35, v2.3.36, v2.3.4, v2.3.5, v2.3.6, v2.3.7, v2.3.8, v2.3.9, v2.4.0, v2.4.1, v2.4.10, v2.4.2, v2.4.3, v2.4.4, v2.4.5, v2.4.6, v2.4.7, v2.4.8, v2.4.9, v2.5.0, v2.5.1, v2.5.10, v2.5.11, v2.5.12, v2.5.2, v2.5.3, v2.5.4, v2.5.5, v2.5.6, v2.5.7, v2.5.8, v2.5.9, v2.6.0, v2.6.1, v2.6.10, v2.6.11, v2.6.12, v2.6.2, v2.6.3, v2.6.4, v2.6.5, v2.6.6, v2.6.7, v2.6.8, v2.6.9, v2.7.0, v2.7.1, v2.7.2, v2.7.3, v2.7.4, v2.7.5, v2.7.6, v2.7.7, v2.7.8, v2.8.0, v2.8.1].
    - Can only install one of: symfony/console[v2.3.0, v3.0.1].
    - Can only install one of: symfony/console[v2.3.1, v3.0.1].
    - Can only install one of: symfony/console[v2.3.10, v3.0.1].
    - Can only install one of: symfony/console[v2.3.11, v3.0.1].
    - Can only install one of: symfony/console[v2.3.12, v3.0.1].
    - Can only install one of: symfony/console[v2.3.13, v3.0.1].
    - Can only install one of: symfony/console[v2.3.14, v3.0.1].
    - Can only install one of: symfony/console[v2.3.15, v3.0.1].
    - Can only install one of: symfony/console[v2.3.16, v3.0.1].
    - Can only install one of: symfony/console[v2.3.17, v3.0.1].
    - Can only install one of: symfony/console[v2.3.18, v3.0.1].
    - Can only install one of: symfony/console[v2.3.19, v3.0.1].
    - Can only install one of: symfony/console[v2.3.2, v3.0.1].
    - Can only install one of: symfony/console[v2.3.20, v3.0.1].
    - Can only install one of: symfony/console[v2.3.21, v3.0.1].
    - Can only install one of: symfony/console[v2.3.22, v3.0.1].
    - Can only install one of: symfony/console[v2.3.23, v3.0.1].
    - Can only install one of: symfony/console[v2.3.24, v3.0.1].
    - Can only install one of: symfony/console[v2.3.25, v3.0.1].
    - Can only install one of: symfony/console[v2.3.26, v3.0.1].
    - Can only install one of: symfony/console[v2.3.27, v3.0.1].
    - Can only install one of: symfony/console[v2.3.28, v3.0.1].
    - Can only install one of: symfony/console[v2.3.29, v3.0.1].
    - Can only install one of: symfony/console[v2.3.3, v3.0.1].
    - Can only install one of: symfony/console[v2.3.30, v3.0.1].
    - Can only install one of: symfony/console[v2.3.31, v3.0.1].
    - Can only install one of: symfony/console[v2.3.32, v3.0.1].
    - Can only install one of: symfony/console[v2.3.33, v3.0.1].
    - Can only install one of: symfony/console[v2.3.34, v3.0.1].
    - Can only install one of: symfony/console[v2.3.35, v3.0.1].
    - Can only install one of: symfony/console[v2.3.36, v3.0.1].
    - Can only install one of: symfony/console[v2.3.4, v3.0.1].
    - Can only install one of: symfony/console[v2.3.5, v3.0.1].
    - Can only install one of: symfony/console[v2.3.6, v3.0.1].
    - Can only install one of: symfony/console[v2.3.7, v3.0.1].
    - Can only install one of: symfony/console[v2.3.8, v3.0.1].
    - Can only install one of: symfony/console[v2.3.9, v3.0.1].
    - Can only install one of: symfony/console[v2.4.0, v3.0.1].
    - Can only install one of: symfony/console[v2.4.1, v3.0.1].
    - Can only install one of: symfony/console[v2.4.10, v3.0.1].
    - Can only install one of: symfony/console[v2.4.2, v3.0.1].
    - Can only install one of: symfony/console[v2.4.3, v3.0.1].
    - Can only install one of: symfony/console[v2.4.4, v3.0.1].
    - Can only install one of: symfony/console[v2.4.5, v3.0.1].
    - Can only install one of: symfony/console[v2.4.6, v3.0.1].
    - Can only install one of: symfony/console[v2.4.7, v3.0.1].
    - Can only install one of: symfony/console[v2.4.8, v3.0.1].
    - Can only install one of: symfony/console[v2.4.9, v3.0.1].
    - Can only install one of: symfony/console[v2.5.0, v3.0.1].
    - Can only install one of: symfony/console[v2.5.1, v3.0.1].
    - Can only install one of: symfony/console[v2.5.10, v3.0.1].
    - Can only install one of: symfony/console[v2.5.11, v3.0.1].
    - Can only install one of: symfony/console[v2.5.12, v3.0.1].
    - Can only install one of: symfony/console[v2.5.2, v3.0.1].
    - Can only install one of: symfony/console[v2.5.3, v3.0.1].
    - Can only install one of: symfony/console[v2.5.4, v3.0.1].
    - Can only install one of: symfony/console[v2.5.5, v3.0.1].
    - Can only install one of: symfony/console[v2.5.6, v3.0.1].
    - Can only install one of: symfony/console[v2.5.7, v3.0.1].
    - Can only install one of: symfony/console[v2.5.8, v3.0.1].
    - Can only install one of: symfony/console[v2.5.9, v3.0.1].
    - Can only install one of: symfony/console[v2.6.0, v3.0.1].
    - Can only install one of: symfony/console[v2.6.1, v3.0.1].
    - Can only install one of: symfony/console[v2.6.10, v3.0.1].
    - Can only install one of: symfony/console[v2.6.11, v3.0.1].
    - Can only install one of: symfony/console[v2.6.12, v3.0.1].
    - Can only install one of: symfony/console[v2.6.2, v3.0.1].
    - Can only install one of: symfony/console[v2.6.3, v3.0.1].
    - Can only install one of: symfony/console[v2.6.4, v3.0.1].
    - Can only install one of: symfony/console[v2.6.5, v3.0.1].
    - Can only install one of: symfony/console[v2.6.6, v3.0.1].
    - Can only install one of: symfony/console[v2.6.7, v3.0.1].
    - Can only install one of: symfony/console[v2.6.8, v3.0.1].
    - Can only install one of: symfony/console[v2.6.9, v3.0.1].
    - Can only install one of: symfony/console[v2.7.0, v3.0.1].
    - Can only install one of: symfony/console[v2.7.1, v3.0.1].
    - Can only install one of: symfony/console[v2.7.2, v3.0.1].
    - Can only install one of: symfony/console[v2.7.3, v3.0.1].
    - Can only install one of: symfony/console[v2.7.4, v3.0.1].
    - Can only install one of: symfony/console[v2.7.5, v3.0.1].
    - Can only install one of: symfony/console[v2.7.6, v3.0.1].
    - Can only install one of: symfony/console[v2.7.7, v3.0.1].
    - Can only install one of: symfony/console[v2.7.8, v3.0.1].
    - Can only install one of: symfony/console[v2.8.0, v3.0.1].
    - Can only install one of: symfony/console[v2.8.1, v3.0.1].
    - Can only install one of: symfony/console[2.0.4, v3.0.1].
    - Can only install one of: symfony/console[2.0.5, v3.0.1].
    - Can only install one of: symfony/console[2.0.6, v3.0.1].
    - Can only install one of: symfony/console[2.0.7, v3.0.1].
    - Can only install one of: symfony/console[v2.0.10, v3.0.1].
    - Can only install one of: symfony/console[v2.0.12, v3.0.1].
    - Can only install one of: symfony/console[v2.0.13, v3.0.1].
    - Can only install one of: symfony/console[v2.0.14, v3.0.1].
    - Can only install one of: symfony/console[v2.0.15, v3.0.1].
    - Can only install one of: symfony/console[v2.0.16, v3.0.1].
    - Can only install one of: symfony/console[v2.0.17, v3.0.1].
    - Can only install one of: symfony/console[v2.0.18, v3.0.1].
    - Can only install one of: symfony/console[v2.0.19, v3.0.1].
    - Can only install one of: symfony/console[v2.0.20, v3.0.1].
    - Can only install one of: symfony/console[v2.0.21, v3.0.1].
    - Can only install one of: symfony/console[v2.0.22, v3.0.1].
    - Can only install one of: symfony/console[v2.0.23, v3.0.1].
    - Can only install one of: symfony/console[v2.0.24, v3.0.1].
    - Can only install one of: symfony/console[v2.0.25, v3.0.1].
    - Can only install one of: symfony/console[v2.0.9, v3.0.1].
    - Can only install one of: symfony/console[v2.1.0, v3.0.1].
    - Can only install one of: symfony/console[v2.1.1, v3.0.1].
    - Can only install one of: symfony/console[v2.1.10, v3.0.1].
    - Can only install one of: symfony/console[v2.1.11, v3.0.1].
    - Can only install one of: symfony/console[v2.1.12, v3.0.1].
    - Can only install one of: symfony/console[v2.1.13, v3.0.1].
    - Can only install one of: symfony/console[v2.1.2, v3.0.1].
    - Can only install one of: symfony/console[v2.1.3, v3.0.1].
    - Can only install one of: symfony/console[v2.1.4, v3.0.1].
    - Can only install one of: symfony/console[v2.1.5, v3.0.1].
    - Can only install one of: symfony/console[v2.1.6, v3.0.1].
    - Can only install one of: symfony/console[v2.1.7, v3.0.1].
    - Can only install one of: symfony/console[v2.1.8, v3.0.1].
    - Can only install one of: symfony/console[v2.1.9, v3.0.1].
    - Can only install one of: symfony/console[v2.2.0, v3.0.1].
    - Can only install one of: symfony/console[v2.2.1, v3.0.1].
    - Can only install one of: symfony/console[v2.2.10, v3.0.1].
    - Can only install one of: symfony/console[v2.2.11, v3.0.1].
    - Can only install one of: symfony/console[v2.2.2, v3.0.1].
    - Can only install one of: symfony/console[v2.2.3, v3.0.1].
    - Can only install one of: symfony/console[v2.2.4, v3.0.1].
    - Can only install one of: symfony/console[v2.2.5, v3.0.1].
    - Can only install one of: symfony/console[v2.2.6, v3.0.1].
    - Can only install one of: symfony/console[v2.2.7, v3.0.1].
    - Can only install one of: symfony/console[v2.2.8, v3.0.1].
    - Can only install one of: symfony/console[v2.2.9, v3.0.1].
    - Installation request for symfony/console == 3.0.1.0 -> satisfiable by symfony/console[v3.0.1].


Installation failed, reverting ./composer.json to its original content.

These are the versions I am running.

$ composer --version
Composer version 1.0-dev (d6ae9a0529e1f39c4c7f9b2f29fff019d79cd1fb) 2015-12-22 20:44:41
$ laravel --version
Laravel Installer version 1.3.1
$ php --version
PHP 5.5.30 (cli) (built: Oct 23 2015 17:21:45) 
$ vagrant --version
Vagrant 1.8.1



via Chebli Mohamed

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

I am getting below error

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

When is it occurring ?

I have a Post route http://localhost/auth/logout When I press the logout button then this action method gets called.

Below is my User model

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

    protected $table = 'tblusers';

    protected $fillable = ['UserName', 'EmailAddress', 'Password', 'RoleID', 'IsActive'];

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

    protected $primaryKey = "UserID";

    public function isClient() 
    {
        return $this->RoleID == \App\Enumeration\Role\RoleType::Client ? 1 : 0;
    }
}

Below is my route.php file

<?php
Route::group(['middleware' => 'web'], function() {

    Route::get('/View-Profile', 'User\Account_Controller@ViewProfile');
    Route::get('/auth/logout', 'Auth\AuthController@getLogout');
});

Question

Am I missing something ?



via Chebli Mohamed

Laravel Socialite HTTPS twitter avatar

I am using laravel 5.0 and utlising the socialite extension to enable twitter login. I encountered a problem with the retrieval of the users twitter profile picture.

The url for the profile picture I receive from twitter is in the following format.

http://ift.tt/1M2NaIZ

This is saved to my db and shown when the user logs into their account. The problem is this image is serving over HTTP and is producing browser warnings when users are accessing their account, as not all the page content is served over HTTPS.

Is there any way to save the twitter profile picture with HTTPS compared to HTTP.

 $user = User::create([
            'provider_id' => $userData->id,
            'name' => $userData->name,
            'username' => $userData->nickname,
            'email' => $userData->email,
            'avatar' => $userData->avatar,
            'active' => 1,
        ]);

I save the user twitter data to my db as shown above and it the $userData->avatar part which is saving the HTTP url.

I can't seem to work a way around this and can't find much documentation on the issue. Any help would be appreciated.



via Chebli Mohamed

Laravel 5. findOrNew for relationships

Just wondering if it is possible that some kind of findOrNew for relationships exist in Eloquent (in case if relationship do not exist attach new model instance)?

What that mean: Lets say that we have devices and specifications tables. Device belongs to specification. Specification_id is an FK (Know that is not best approach, but I have something like this left by previous programmer). Under id 11 we have device that do not have specification but we have to display that for user anyway.

$device = Device::find(11);
echo $device->specification->cpu;

In this case it will throw an error because specification will be null - it do not exist for device with id 11.

Know that I could check first if it exist but there a a lot of similar lines and app is pretty big. I need to move it from Kohana to Laravel. It works in Kohana because empty object is loaded then and 2nd line just return null. For Laravel I can just check if relationship exist and load new model then but I am curios if maybe there is any other and better way?



via Chebli Mohamed

Laravel 5 Task Scheduling runs a task evey minute, regardless of method invoked

I'm puzzled by a weird Laravel 5 behaviour. I added this to the \app\Console\Kernel.php:

protected function schedule(Schedule $schedule)
{
    //$schedule->command('inspire')->hourly();
    $schedule->command(Utilsclass::log_line("CROM JOB EXECUTED @ ".date('l jS \of F Y h:i:s A')))->monthly();
}

and I expect to see an activity on my log once a month, but this is what I get on log.txt:

CROM JOB EXECUTED @ Tuesday 29th of December 2015 03:32:01 PM

CROM JOB EXECUTED @ Tuesday 29th of December 2015 03:33:01 PM

CROM JOB EXECUTED @ Tuesday 29th of December 2015 03:34:01 PM

CROM JOB EXECUTED @ Tuesday 29th of December 2015 03:35:01 PM

CROM JOB EXECUTED @ Tuesday 29th of December 2015 03:36:01 PM

CROM JOB EXECUTED @ Tuesday 29th of December 2015 03:37:01 PM

CROM JOB EXECUTED @ Tuesday 29th of December 2015 03:38:02 PM

CROM JOB EXECUTED @ Tuesday 29th of December 2015 03:39:01 PM

CROM JOB EXECUTED @ Tuesday 29th of December 2015 03:40:01 PM

so every minute, regardless of the method used. In fact using daily() or hourly() makes no difference at all.

Besides being quite new to Laravel I don't know how to hunt down a problem, which seems something like a bug to me...

Any help?



via Chebli Mohamed

Fill extra column for User

I have a user table with a referral column and this code in controller/auth:

protected function create(array $data)
    {

        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'referral' => md5($data['email']),
            ]);
    }

It adds a name, email and password but not referral.

There is no error or notice. What should I do to fill also referral column?



via Chebli Mohamed

bind laravel app authentican to another laravel app authentican

I have two laravel app and each has separate authentication (login), now what I want is when the user successfully login to my first laravel app (login laravel app) then the second laravel app (serve as the main app) will authenticate the current logged user (successfully login). It's some sort of a global authentication where I have single separate login laravel app to be used in login and once use has logged in to that laravel app then he can automatically logged to any other app that was bind to that login app. Any ideas, clues, suggestions, recommendations, help please?



via Chebli Mohamed

Laravel 5.2 update/insert batch similar to Codeigniter's update_batch/insert_batch()

Does laravel have an update batch functionality similar to Codeigniter?

Codeigniter uses $this->db->update_batch('mytable', $data, 'title'); to do a batch update. More info could be found here.

But as for laravel's update, it seems that it could only do a single transaction. I feel that this is kind of bad when you have multiple rows to update wherein it will be inside a for loop. Something similar to this:

foreach ($rows => $row) {
    DB::table('users')->where('id', $row['row_id'])->update(['votes' => 1]);
}

For atleast you get the picture, right?

If you'll look into this code, your database could get knock out pretty much as it keeps on connecting unlike the update_batch(), only a single transaction is being throw.



via Chebli Mohamed

Laravel Storage returns: mkdir(): File exists

When ill try to check if a file exists in Laravel 5.1 i am always getting this error:

ErrorException in Local.php line 95: 
mkdir(): File exists

I dont know what could here be wrong, i want to check if a file exists or not with:

$exists = Storage::disk('images')->has('filename.jpg');

dd($exists);

Disk "images":

'disks' => [

    'local' => [
        'driver' => 'local',
        'root'   => storage_path().'/app',
    ],

    'images' => [
        'driver' => 'local',
        'root'   => storage_path().'/app/images',
    ],

Any ideas?



via Chebli Mohamed

Running Laravel queues automatically

I have implemented Laravel queue.The thing is i have to run the command php artisan queue:listen every time.Is there any way that the jobs get executed automatically without running any command.



via Chebli Mohamed

how i can use paginate() after get() ?

i'm need to use paginate but i used get() before for some reasons so how i can use paginate() after get() ? when i try

$s   = Lists::where('id','>',500)->get();
             $s = $s->paginate(2);
            var_dump($s);

i get

Call to undefined method Illuminate\Database\Eloquent\Collection::paginate();

i do every thing go skip get() before but it's big problem any one have any idea

sample



via Chebli Mohamed

Method not found error in laravel

I am stuck in this error in laravel.

BadMethodCallException in View.php line 380: Method [middleware] does not exist on view.

Any idea on this, that any core file has been disturbed ?



via Chebli Mohamed

Laravel 5.2 - Auth::login not preserve when using new \App\User

I've used these code to authenticate username from external source, but laravel 5.2 not save the authentication, and request the external source every time.

class Authenticate
{
    public function handle($request, Closure $next, $guard = null)
        {
            if (Auth::guard($guard)->guest()) {
                if ($request->ajax()) {
                    return response('Unauthorized.', 401);
                } else {
                    $username = getFromExternalSource();
                    if($username==null){ redirect()->guest('auth/login'); }
                    $user = new \App\User(['username'=>'admin']);
                    Auth::login($user);
                }
            }

            return $next($request);
        }
}

But when I change Auth::login using $user model get from database it work, I don't know why:

$userDB = \App\User::where('username','=','admin')->first();
Auth::login($userDB);



via Chebli Mohamed

multiple file upload laravel 5 and move to folder

I'm trying to upload multiple files and store the name in the database, and the file in the storage/thumbnail folder. The problem is that the move function is not working because the file that has to be moved is empty. However when I DD my results, all images show up.

here's my code:

$files = Input::file('images'); //The array with images

The loop to put all images to the storage folder:

foreach ($files as $file) {
    Input::file($file)->move('storage/thumb_nail');
}

When i dd($file) inside the loop it shows the image object like this:

UploadedFile {#30 ▼
   -test: false
   -originalName: "IMG_0180.JPG"
   -mimeType: "image/jpeg"
   -size: 1331799
   -error: 0
}

Any suggestions?



via Chebli Mohamed

How to change the redirect method and payload that Laravel's validate return?

I have a problem with validation - if validation fails I get an error.

Route::get('list', 'MainController@list');
Route::post('search', 'MainController@search');
Route::post('create', 'MainController@create');

list shows the full item list and a search form. The form posts to search. search returns a list of items (search results) and the form with two buttons - either search again or create new item. This form posts to create but it calls search method if Search button was pressed. If form was submitted using Create button, the input is validated. This is simplified version of my create method:

public function create(Request $request)
{
    if ($request->has('search'))
        return $this->search($request);

    $this->validate($request, [
        'name' => 'required'
    ]);

    return 0;
}

If search was clicked it all works. If validation passes it all works (and I can include the logic instead of return 0;). But if validation fails I get the following error:

MethodNotAllowedHttpException in RouteCollection.php line 219:
in RouteCollection.php line 219
at RouteCollection->methodNotAllowed(array('POST')) in RouteCollection.php line 206
at RouteCollection->getRouteForMethods(object(Request), array('POST')) in RouteCollection.php line 158
at RouteCollection->match(object(Request)) in Router.php line 802
at Router->findRoute(object(Request)) in Router.php line 670
at Router->dispatchToRoute(object(Request)) in Router.php line 654
at Router->dispatch(object(Request)) in Kernel.php line 246
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in Kernel.php line 132
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99
at Kernel->handle(object(Request)) in index.php line 53

Problem seems to be tied to routing and indeed browsers debugger shows that it's sending a GET request.

I tried to investigate Laravel's validator implementation but couldn't really understand the flow and find where the request is returned. Is there any chance to affect it in a way so that client gets the result of previous POST again?

If I try to allow GET requests on my search, problem is partially solved. If I search from the full list and then click Create, validation returns me to search again. With no results though so I should still implement some kind of "if validation fails, process this as search request". Well, ok, but I still need what was posted...

If, however, I use the Search again button which posts to create and returns the same view, the validator redirects to GET the create route which gives me more problems to deal with.



via Chebli Mohamed