samedi 30 avril 2016

How to append to result in Laravel 5.1

I try to return my search result into array to show in blade but get error :

$persons = persons::where('name','like',"%$search_term%")->lists('id');

foreach($persons as $person)
{
       $trials = trial::with('samples')->with('persons')->where('persons_id', '=', $person)->get();
}

FatalErrorException in 0bfe77047992e2dce86ae561e266494c line 37: Call to undefined method Illuminate\Database\Eloquent\Collection::appends()

I try to this with + array, but get errors



via Chebli Mohamed

Is there any way to do Partial page refresh on page load without writing JQuery in Laravel?

I know both .NET and PHP and as per my understanding EntityFramework in .NET is same thing as Laravel in PHP.

in .NET we have @using (Ajax.BeginForm that renders forms same as {!! Form::open in PHP.

@using (Ajax.BeginForm does not refresh the whole page on form submit and I don't need to write JQuery to do this. So, basically it acts same as JQuery.ajax

Question: Is there any way to do Partial page refresh on form submit without writing JQuery in Laravel?



via Chebli Mohamed

Laravel 5.1 .env file not recognized

I upload laravel 5.1 project in Host. and I Check the .env file with this code.

Route::get('/', function() {
    dd(env('APP_KEY'));
});

But Returned Null. How to connect .env in laravel on host? and my php version is 5.6



via Chebli Mohamed

Laravel 5.1 validating array of files now working

I am trying to validate an array of files to check that they are the right mime type but it's not working I get the following error:

Undefined index: files.0

I get what this error is trying to tell me but I don't understand why it is happening. Here is what I am submitting:

------WebKitFormBoundary8wDAKRGDzd5kLrTO
Content-Disposition: form-data; name="files[]"; filename="eye design.png"
Content-Type: image/png


------WebKitFormBoundary8wDAKRGDzd5kLrTO
Content-Disposition: form-data; name="files[]"; filename="hd flamingo.tif"
Content-Type: image/tiff


------WebKitFormBoundary8wDAKRGDzd5kLrTO
Content-Disposition: form-data; name="files[]"; filename="Picture 3.tif"
Content-Type: image/tiff


------WebKitFormBoundary8wDAKRGDzd5kLrTO
Content-Disposition: form-data; name="files[]"; filename="Picture 16.tif"
Content-Type: image/tiff


------WebKitFormBoundary8wDAKRGDzd5kLrTO
Content-Disposition: form-data; name="files[]"; filename="Picture 23.tif"
Content-Type: image/tiff


------WebKitFormBoundary8wDAKRGDzd5kLrTO--

Here is my request:

<?php namespace App\Http\Requests;

use Response;
use Illuminate\Foundation\Http\FormRequest;

class UploadRequest extends FormRequest
{
    public function rules()
    {
        $rules = [];
        foreach($this->files as $key => $file) {
            $rules['files.'.$key] = 'required|image|mimes:jpeg,png,gif';
        }
        return $rules;
    }

    public function messages()
    {
        $messages = [];

        foreach($this->files as $key => $file) {
            $messages['files.'.$key.'.required'] = 'You must upload a file.';
            $messages['files.'.$key.'.image'] = 'The upload file must be an image.';
            $messages['files.'.$key.'.mimes'] = 'The image must be one of the following types: JPEG, PNG, or GIF.';
        }
        return $messages;
    }

    public function authorize()
    {
        return true;
    }

}

And inside the rules method of my request if I do print_r($this->files) this is what I get:

Symfony\Component\HttpFoundation\FileBag Object
(
    [parameters:protected] => Array
        (
            [files] => Array
                (
                    [0] => Symfony\Component\HttpFoundation\File\UploadedFile Object
                        (
                            [test:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 
                            [originalName:Symfony\Component\HttpFoundation\File\UploadedFile:private] => eye design.png
                            [mimeType:Symfony\Component\HttpFoundation\File\UploadedFile:private] => image/png
                            [size:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 812968
                            [error:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 0
                            [pathName:SplFileInfo:private] => C:\xampp\tmp\php4898.tmp
                            [fileName:SplFileInfo:private] => php4898.tmp
                        )

                    [1] => Symfony\Component\HttpFoundation\File\UploadedFile Object
                        (
                            [test:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 
                            [originalName:Symfony\Component\HttpFoundation\File\UploadedFile:private] => hd flamingo.tif
                            [mimeType:Symfony\Component\HttpFoundation\File\UploadedFile:private] => image/tiff
                            [size:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 4579592
                            [error:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 0
                            [pathName:SplFileInfo:private] => C:\xampp\tmp\php48A9.tmp
                            [fileName:SplFileInfo:private] => php48A9.tmp
                        )

                    [2] => Symfony\Component\HttpFoundation\File\UploadedFile Object
                        (
                            [test:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 
                            [originalName:Symfony\Component\HttpFoundation\File\UploadedFile:private] => Picture 3.tif
                            [mimeType:Symfony\Component\HttpFoundation\File\UploadedFile:private] => image/tiff
                            [size:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 4158508
                            [error:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 0
                            [pathName:SplFileInfo:private] => C:\xampp\tmp\php48B9.tmp
                            [fileName:SplFileInfo:private] => php48B9.tmp
                        )

                    [3] => Symfony\Component\HttpFoundation\File\UploadedFile Object
                        (
                            [test:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 
                            [originalName:Symfony\Component\HttpFoundation\File\UploadedFile:private] => Picture 16.tif
                            [mimeType:Symfony\Component\HttpFoundation\File\UploadedFile:private] => image/tiff
                            [size:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 6080280
                            [error:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 0
                            [pathName:SplFileInfo:private] => C:\xampp\tmp\php48DA.tmp
                            [fileName:SplFileInfo:private] => php48DA.tmp
                        )

                    [4] => Symfony\Component\HttpFoundation\File\UploadedFile Object
                        (
                            [test:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 
                            [originalName:Symfony\Component\HttpFoundation\File\UploadedFile:private] => Picture 23.tif
                            [mimeType:Symfony\Component\HttpFoundation\File\UploadedFile:private] => image/tiff
                            [size:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 4279880
                            [error:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 0
                            [pathName:SplFileInfo:private] => C:\xampp\tmp\php48EA.tmp
                            [fileName:SplFileInfo:private] => php48EA.tmp
                        )

                )

        )

)



via Chebli Mohamed

vendredi 29 avril 2016

How to get laravel (file) cached key expiration time?

is there way to get time left to cache key expires? Currently i'm using Laravel file driver.

br Y



via Chebli Mohamed

Laravel 5.1 - Create user using Socialite and set confirmed column to 1

I've got socialite working really well in my Laravel app. I do however have one small issue.

By default, all accounts have a confirmed column that is set to 0, as some users are using social profiles, I would like to set their confirmed column to 1 instantly after successful integration with their social profile.

This is my column code from my migration:

Schema::table('users', function (Blueprint $table) {
    $table->boolean('confirmed')->default(0);
    $table->string('confirmation_code')->nullable();
});

And this is my create code inside my socialite auth controller:

$new_user = User::create([
    'name' => $user->name,
    'email' => $user->email,
    'oauth_facebook_id' => $provider === 'facebook' ? $user->id : NULL,
    'oauth_twitter_id' => $provider === 'twitter' ? $user->id : NULL,
    'confirmed' => 1,
    'avatar' => $user->avatar
]);

Even though confirmed is set to 1, it still makes the account with a 0.

Am I missing something?

Andy



via Chebli Mohamed

Common method for Android and Website : Laravel 5.2

I have following method in controller.

private function SaveChanges(\App\Http\Requests\CountryRequest $request) {
    $Object = array(
        'Country'     =>  $request['Country'],
        'CountryCode' =>  $request['CountryCode'],
        'CountryID'   =>  $request['CountryID']
    );
    if($request['CountryID'] == 0) {
        $result = (new \App\DataAccess\CData())->CreateCountry(json_encode( $CObject ));
    }
    return redirect()->route($this->AllCountries);
}

Below is the Request class

class CountryRequest extends Request
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'Country'       => 'required|max:25|min:5|unique:tblcountry,Country,'. 
                                   \Request::get('CountryID') . ',CountryID',
            'CountryCode'   => 'required|max:5|min:2|unique:tblcountry,CountryCode,'.
                                   \Request::get('CountryID') . ',CountryID',
        ];
    }
}

Below is the method that will save the record in database.

class CountryData {

    public function CreateCountry($CountryObject) {
        $obj = json_decode($CountryObject);
        $Country = new \App\Models\CountryModel();
        $Country->Country       = $obj->Country;
        $Country->CountryCode   = $obj->CountryCode;
        $Country->save();
        return true;
    }
}

I have confusion in the flow. Below are my confusions.

I have to develop a website and an Android App. Android App will call Laravel method to fetch data. JSON data will be received and send to Laravel through Android. In order to achieve this, I removed save code from Controller action method and placed in a class called CountryData as given above.

I am assuming that there will be two routes to save the data.

  1. For Android App to return JSON result after save.
  2. For Website to redirect to a View after save.

What's the confusion?

I have Request class in Controller Action method to make sure max and min char validation and Duplicate check. But this is being done in the Controller Action method and will work for the website.

Android App will also need above validation. So Do I need validation at two places?



via Chebli Mohamed

Connection could not be established with host smtp.gmail.com [Permission denied #13]

I am developing using Laravel-5.1. I have the .env config file working properly on development environment which is windows 8, 4GB RAM. When I deployed to the remote server which is Centos-6, I began to get this error :

Swift_TransportException in StreamBuffer.php line 265:
Connection could not be established with host smtp.gmail.com [Permission denied #13]
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
at Swift_Mailer->send(object(Swift_Message), array()) in Mailer.php line 395
at Mailer->sendSwiftMessage(object(Swift_Message)) in Mailer.php line 181
at Mailer->send('email.verify', array('users' => object(User), 'confirmation_code' => 'kdsEeEcS0wGI6YYyzPJqwa0ZM0i10t'), object(Closure)) in Facade.php line 222
at Facade::__callStatic('send', array('email.verify', array('users' => object(User), 'confirmation_code' => 'kdsEeEcS0wGI6YYyzPJqwa0ZM0i10t'), object(Closure))) in UserController.php line 70
at Mail::send('email.verify', array('users' => object(User), 'confirmation_code' => 'kdsEeEcS0wGI6YYyzPJqwa0ZM0i10t'), object(Closure)) in UserController.php line 70
at UserController->store(object(UserRequest))
at call_user_func_array(array(object(UserController), 'store'), array(object(UserRequest))) in Controller.php line 256
at Controller->callAction('store', array(object(UserRequest))) in ControllerDispatcher.php line 164
at ControllerDispatcher->call(object(UserController), object(Route), 'store') in ControllerDispatcher.php line 112
at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 114
at ControllerDispatcher->callWithinStack(object(UserController), object(Route), object(Request), 'store') in ControllerDispatcher.php line 69
at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\UserController', 'store') in Route.php line 203
at Route->runWithCustomDispatcher(object(Request)) in Route.php line 134
at Route->run(object(Request)) in Router.php line 708
at Router->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Router.php line 710
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 675
at Router->dispatchToRoute(object(Request)) in Router.php line 635
at Router->dispatch(object(Request)) in Kernel.php line 236
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 VerifyCsrfToken.php line 50
at VerifyCsrfToken->handle(object(Request), object(Closure))
at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 49
at ShareErrorsFromSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in StartSession.php line 62
at StartSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure))
at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
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 103
at Pipeline->then(object(Closure)) in Kernel.php line 122
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 87
at Kernel->handle(object(Request)) in index.php line 54

This is the .env config file:

APP_ENV=local
APP_DEBUG=true
APP_KEY=app_key_many_digits

DB_HOST=remotehost
DB_DATABASE=mydatabase
DB_USERNAME=mysqlusername
DB_PASSWORD=mysqlpassword

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=myemail@gmail.com
MAIL_PASSWORD=mypassword
MAIL_ENCRYPTION=tls

I don't know if by default smtp is configured on Centos-6 or I'll need to configure it, if I am then please tutor me on how to do this.



via Chebli Mohamed

PHP - Getting numbers when reading korean characters

I have following url with some Korean characters at end of the url:

http://localhost/example/popular-tags/고양이

Now I am reading 고양이 from url like this which is used in Laravel5 for read data from url string:

$TagName = str_slug(Request::segment(2), "-");

but getting number eab3a0ec9691ec9db4 not 고양이 characters.

Any idea how to get Korean characters.

Thanks.



via Chebli Mohamed

Eloquent pivot : how to do select columns in Laravel 5.1

I have two models Bill & Order, I can get Orders records via :

    $orders = $bill->orders;

But I want to use select like this :

 $orders = $bill->orders->select([
                            'orders.*',                            
                            \DB::raw('sum(orders.quantity) as qty'),
                            \DB::raw('sum(orders.price) as  total')                            
                            ]) 
                            ->groupBy('article_id');

I get this error :

Method select does not exist.

Please any one may help me, thanks !



via Chebli Mohamed

How to Queued Event Listeners to Amazon SQS in Laravel

I follow the Laravel Document ( http://ift.tt/1WuxqUX ) to create an event listener and implement the \Illuminate\Contracts\Queue\ShouldQueue contract:

use App\Events\SomeEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class EventListener implements ShouldQueue
{
    public function __construct()
    {
        //
    }

    public function handle(SomeEvent $event)
    {
        $event->show();
        return false;
    }
}

and following is my listener:

use App\Events\SomeEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class EventListener implements ShouldQueue
{
    public function __construct()
    {
        //
    }

    public function handle(SomeEvent $event)
    {
        $event->show();
        return false;
    }
}

and I use the global event helper function to fire event:

event(new SomeEvent('Hello World'));

the event listener really be queued automatically to Redis.

But the document not describe how to queue the event listener to the Amazon SQS. How am i supposed to actually push the event listener method to the Amazon SQS ?

Any help is appreciated.



via Chebli Mohamed

Laravel schedule on azure web app

I am looking for a way to link an azure scheduler or web job to the laravel schedule.

My understanding is, to set up an azure schedule I would need an end point to link to my laravel which i am not sure how to achieve that.



via Chebli Mohamed

jeudi 28 avril 2016

Check for composite unique input via Request in Laravel

I have a site that has multiple instances (companies).

Each company can add their own inventory and unit number must be unique within instance (company). But I want to allow same unit number per company. Therefore, unit+ instance_id needs to be unique. Is there a way to implement this check in Request rules?

public function rules() {
    return [
        'unit' => 'unique:mytable|required|max:45',
        'comments' => 'sometimes|max:255'
    ];
}

public function messages() {
    return [
        'unit.unique' => 'Unit number already exists!',
        'unit.required' => 'Enter Unit Number!',
        'max' => ':attribute - Should not be longer than 255 symbols!'
    ];
}



via Chebli Mohamed

Laravel Output Associated Tags

I have an application in Laravel 5.1, my application allows the user to add an article and choose a number of categories associated to that article.

I save the relationship between the article in an association table and I now want to output on the user's articles page all the articles the user has submitted but at the side of the title show the categories the article is within.

the articles page will list all the articles so the list has to be unique.

my controller:

public function index()
    {
        $articles = DB::table('articles')
                    ->leftjoin('w_relations','w_relations.article_id','=','articles.id')
                    ->leftjoin('articlecategories','articlecategories.id','=','w_relations.type_id')
                    ->where('articles.comp_id',Auth::user()->comp_id)->get();

        return view('advertiser/workshops', compact('workshops'));
    } 

my view

<ul>
@foreach($articles as $a)
    <li> | </li>
@endforeach
</ul>

I thought the above would output

Article 1 | History, Category, Category2

but instead I get

Article 1 | History Article 
1 | Category Article 
1 | Category2

I can kind of see where I'm going wrong but I don't know how to fix the query?



via Chebli Mohamed

Why I get PHP Catchable fatal error in composer update & when I try to run php artisan

I know same question. But no aswer for that questions. that's why I asked it again. Here is my error in the composer.

PHP Catchable fatal error:  Argument 2 passed to
Illuminate\Routing\UrlGenerator::__construct()
must be an instance of Illuminate\Http\Request, null given, called in
D:\working_Dir\htdocs\license_engine\vendor\laravel\framework\src\Illuminate\Routing\RoutingServiceProvider.php
on line 62 and defined in D:\working_Dir\htdocs\license_engine\vendor\laravel\framework\src\Illuminate\Routing\UrlGenerator.php on line 102

I did everything that I know. Please tell me anything to do.



via Chebli Mohamed

laravel 5.1 - SQLSTATE[HY000] [2002] A connection attempt failed.. - when attempt to connect from Local to remote server

env file:

APP_ENV=local
APP_DEBUG=true
APP_KEY= ...........

DB_HOST=srv3.linuxisrael.co.il
DB_DATABASE= name_of_my_database
DB_USERNAME=moti_winkler
DB_PASSWORD=1234567890

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

Routes.php :

use App\User;

Route::get('/', function(){
    User::create(['first_name' => 'moti']);
    return view('welcome');
});

The error i get :

PDOException in Connector.php line 55:

SQLSTATE[HY000] [2002] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

My problem is that:

I'm trying to connect from my computer - to my remote MySQL server

And I don't understand why it doesn't work ?

What should I do to connect ?

What am I missing ?

Thanks



via Chebli Mohamed

CSRF Token not working in Laravel 5.1 Exceptions Handler with an Ajax request

I have a Laravel 5.1 application with Ajax content loaded at start up.

I have placed the CSRF meta tag to page head:

<meta name="csrf-token" content="" />

And I use it in jquery ajax requests:

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

Everything works perfectly under normal circumstances. But when I open a 404 error page without a previous session, my ajax requests get an error: TokenMismatchException in VerifyCsrfToken.php

I have an 404 error handler in file: app\Exceptions\Handler.php

public function render($request, Exception $e)
{
  if ($e instanceof NotFoundHttpException)
  {
    $foo = \App\Foo::foo();
    return \Response::make(view("errors.404", compact("foo")), 404);
  }

  return parent::render($request, $e);
}

I can repeat this error by opening a private browser window and opening my site with an url to a non existing page. It persists on page reloads. But if I go to an existing page and try the 404 url again, it works fine.

Any ideas how fix this problem?



via Chebli Mohamed

Laravel issue with Carbon throwing an exception

Hi so i'm following the Laracasts But i'm pretty stuck because i'm not sure why i'm getting the error ~: Method Carbon\Carbon::__toString() must not throw an exception

here is my code;

<?php

namespace App\Http\Controllers;


use App\Http\Requests\CreateArticleRequest;
use App\Article;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use Request;
use Carbon\Carbon;

class ArticlesController extends Controller
{
public function index()    {
    $articles= article::all();

   return view ('articles.index',compact ('articles')); 
}

public function show($id){

  $article= article::findOrFail($id);

   return view ('articles.show',compact ('article')); 

}

public function create(){

    return view('articles.create');

}

public function store(Request $request){
    $input = Request::class;
    $input['published_at'] = Carbon::now();

    Article::create($input);

    return redirect('articles');
}

}
}

and here is my front end:

@extends ('app')

@section('content')

<h1> Write a New Article </h1>

<hr/>


{!! Form::open(['url' => 'articles']) !!}
<div class="form-group">
    {!! Form::label('title', 'Title:') !!}
    {!! Form::text('title', null, ['class' => 'form-control']) !!}

</div>
<!-- FORM INPUT HEEEEERREEEE -->
<div class="form-group">
    {!! Form::label('body','Body:') !!}
    {!! Form::textarea('body', null, ['class' => 'form-control']) !!}

</div>

<!-- Add Article field -->
<div class="form-group">
    {!! Form::submit('Add Article',['class' => 'btn btn-primary form-control'] ) !!}

</div>

{!! Form::close() !!}


@stop



via Chebli Mohamed

Laravel 5.1: Auth::logout() is not working and BindingResolutionsException is not instantiable error

I'm new in laravel and I try to build a simple Authentication. All the things works fine except when using AuthController's action to log out, it just simply doesn't work. I have a nav bar which checks for Auth::check() and it doesn't change after calling the log out action and it stocks in home page. but after making few changes like deleting this manual logout code in SessionController:

public function logout()
    {
        Auth::logout();
        Session::flush();
        return redirect()->intended('login');
    }

and changing the rout from this:

Route::get('logout', 'SessionsController@logout');

to this:

Route::get('auth/logout', 'Auth\AuthController@logout');

it throws this error:

BindingResolutionException in Container.php line 749: Target [Illuminate\Contracts\Auth\Registrar] is not instantiable. 

I have this route inside the routes.php file:

Route::get('auth/logout', 'Auth\AuthController@logout');

and my AuthController is the controller that laravel providing us.

my SessionsController that handled logout before the changes but actually not work either is:

<?php namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class SessionsController extends Controller
{
    /**
     * Create a new sessions controller instance.
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Show the login page.
     *
     * @return \Response
     */
    public function login()
    {
        return view('auth.login');
    }

    /**
     * Perform the login.
     *
     * @param  Request  $request
     * @return \Redirect
     */
    public function postLogin(Request $request)
    {
        $this->validate($request, ['username' => 'required|exists:users', 'password' => 'required']);

        if ($this->signIn($request)) {
            flash('Welcome back!');

            return redirect()->intended('dashboard');

        }

        flash('Could not sign you in.');

        return redirect()->back();
    }

    /**
     * Destroy the user's current session.
     *
     * @return \Redirect
     */
    public function logout()
    {
        Auth::logout();
        Session::flush();
        return redirect()->intended('login');
    }

    /**
     * Attempt to sign in the user.
     *
     * @param  Request $request
     * @return boolean
     */
    protected function signIn(Request $request)
    {
        return Auth::attempt($this->getCredentials($request), $request->has('remember'));
    }

    /**
     * Get the login credentials and requirements.
     *
     * @param  Request $request
     * @return array
     */
    protected function getCredentials(Request $request)
    {
        return [
            'username' => $request->input('username'),
            'password' => $request->input('password'),
            'verified' => true
        ];
    }


}

And here is the AuthController __construct method:

public function __construct(Guard $auth, Registrar $registrar)
    {
        $this->auth = $auth;
        $this->registrar = $registrar;
        $this->middleware('guest', ['except' => ['logout', 'getLogout']]);

    }

Please help me as soon as possible. Any help would be appreciated.



via Chebli Mohamed

mercredi 27 avril 2016

Laravel 5.1 retrieve multiple input value and insert to db

I have an input form named category that can have multiple value just like tags input form in stackoverflow when you asking a question
I want to get all input value from that form and insert it into category_service pivot table
I use $category = implode(",", Input::get('category')); to get the array value
And then i get Invalid argument supplied for foreach() error when try to insert it using this code:

foreach ($category as $category) {
    DB::insert('INSERT INTO category_service (category_id, service_id) VALUES (?,?)', array('$category', $service->id));
}



via Chebli Mohamed

Laravel 5.2 over EC2, CSS is not loading

I am new to laravel, i pushed all the code to EC2 but when i change anything in my app.css file, my changes are not coming to user although app.css on EC2 have all those changes.

Please help! Thanks



via Chebli Mohamed

Integrating paymnet gateway "Instamojo" in Laravel 5.1

I'm using a package 'IndiPay' (http://ift.tt/1rB6V5a) in Laravel 5.1. I have configured api_key and auth_token in my .env file. And in the parameters list, included the required POST parameters (purpose and amount). Additionally, added tid with reference to the GitHub. Even though, I couldn't make the payment successful. It throwed an error like problem in Hash parameter. I attach my screenshot here.

enter image description here

Any suggestions please?

Thanks in advance..



via Chebli Mohamed

after install auth2.0 server Laravel5.1 give an server error

I have successfully installed Laravel5.1 localhost/myproject/public link is working well.

After that I installed Auth2.0 server accroding to this. http://ift.tt/1NVuhqC

After install and configure I called the url http://localhost/myproject/public/oauth/access_token and its giving 500 server error for all the url with http://localhost/myproject/public

Can anyone help me please.

Thanks.



via Chebli Mohamed

Laravel pagination render() not working.

I have a controller que find the products and return to view . Current i'm trying make the pagination and i'm using the following code :

return $this->queryProductsAvailable()
                ->where('fornecedores.plano_id', $plano)
                ->select('produtos.*')
                ->paginate( $limit );      

function queryProductsAvailabe:

private function queryProductsAvailable()
{   
   return Products::join('fornecedores', 'fornecedores.id', '=' ,'produtos.fornecedor_id')
                        ->where( 'fornecedores.ativo', '1')
                        ->where( 'produtos.moderacao', 'P' )
                        ->where( 'produtos.ativo' , '1' )  
                        ->where( 'produtos.preco_min', '>', 0 )
                        ->select( 'produtos.*');                   
}

To view i'm return the following:

return view('Catalogo.index', 
                    [ 
                        'products' => $products
                    ] 
                );

But when i run the method $products->render()nothing happens.
No errors, no messages...
if i run $products->total() is returned the value 0
if i run $products->nextPageUrl() nothing happens

The same variable used to access this methods is used for the loop and print of products and the foreach works fine.

if i access the url with /?page=2 the pagination works, but not render list of pages.

Any idea?



via Chebli Mohamed

How to track changes in the database and store it in a history log (Laravel 5.1)

I have hook to track changes in database. I used this hook in app/helpers.php. i want to know how to call this function and use this after insert, update and saving.

helpers.php

function loggerAuditing($model)
{
    $changes = array();
    foreach($model->getDirty() as $key => $value){
        $original = $model->getOriginal($key);
        $changes[$key] = [
            'old' => $original,
            'new' => $value,
        ];
    }
}



via Chebli Mohamed

Evernote Cloud SDK 2.0 for PHP and Laravel 5.1

I am trying to integrate the evernote/evernote-cloud-sdk-php package on a Laravel v5.1.30 app.

I tried installing it via composer with composer require evernote/evernote-cloud-sdk-php dev-master and with composer require evernote/evernote-cloud-sdk-php but had no success. Even though I've set the "minimum-stability": "dev" in my composer.json I am still getting

Problem 1
- Installation request for evernote/evernote-cloud-sdk-php dev-master -> satisfiable by evernote/evernote-cloud-sdk-php[dev-master].
- evernote/evernote-cloud-sdk-php dev-master requires ezyang/htmlpurifier ~4.6.0 -> no matching package found.

In my composer.json file I already have a "ezyang/htmlpurifier": "^4.7" entry. It seems to be a dependency for laravel.

$> composer depends ezyang/htmlpurifier
laravel/laravel dev-integrate_evernote requires ezyang/htmlpurifier (^4.7)

Any ideas on how I could do this integration?



via Chebli Mohamed

Laravel 5.1 Ajax file upload

I am trying to upload multiple files with AJAX using jFiler package. I have a form where users upload files and have a preview for images and videos that are uploaded. And then when the user later fills up the rest of the form, and submits it, I want to save the paths of the files in the database, with the id of the article they belong to. I am therefore saving file path to session in my controller and saving it to DB like this:

//save article to DB
public function store(Create $request) {
  $slug = str_slug($request['name']);
  $count = Article::where('slug', 'like', '%'.$slug.'%')->count();

  if($count)
    $slug = $slug .'-'. $count;

  $article = Article::create(array_merge($this->fillobject($request), $data));

  //store external media for the article
  $externalMedia = ExternalMedia::create([
    'url' => $request->input('external_media'),
    'article_id' => $article->id
    ]);


  //if files are uploaded store call fileUpload and store files
  $this->fileUpload(Session::get('filePath'), $article->id);

  return Redirect::route('admin.articles.show',['id'=>$article->id]);
}

public function fileUpload($files, $id) {

  $articleMedia = [];
  $articleMediaFiles = Media::where('article_id', $id)->get(['path']);

  foreach($articleMediaFiles as $articleMediaFile) {
    $articleMedia[] = $articleMediaFile->path;
  }

  foreach($files as $file) {
    $oldPath = explode('articles/', $file);
    $directoryPath = $oldPath[0].'articles/'.$id;
    $newPath =  explode('public/',   $oldPath[0].'articles/'.$id.'/'.$oldPath[1]);

    if(!File::exists($directoryPath))
      File::makeDirectory($directoryPath, 0755, true);



    if(!in_array($newPath[1], $articleMedia))
      Media::create(['path' => $newPath[1], 'article_id' => $id]);

    Image::make($file)->resize(100, 100)->save($newPath[1]);
  }
}

public function ajaxUpload() {
  $name = "";
  $path = public_path('files/uploads/articles/');

  if (Input::hasFile('file')) {
    $files = Input::file('file');

    foreach($files as $file){
      $filePath[] = $path.$file->getClientOriginalName();
      Image::make($file)->resize(100, 100)->save($path.'/'.$file->getClientOriginalName());
    }
        Session::put('filePath', $filePath);
        return json_encode($filePath);
  }
}

My issue with this code is that I only save one file path to DB when uploading multiple files.



via Chebli Mohamed

Laravel count results on specific date and column

In my database I am having the following records:

id    code   product_amount         created_at
 1    ORD-1      250          2016-04-04 05:15:05 PM
 2    ORD-1      150          2016-04-04 05:15:05 PM
 3    ORD-2      450          2016-04-05 11:18:17 PM
 4    ORD-3      250          2016-04-06 04:30:25 PM
 5    ORD-3      300          2016-04-06 04:30:25 PM
 6    ORD-3      750          2016-04-06 04:30:26 PM
 7    ORD-4      650          2016-04-06 08:30:26 PM
 7    ORD-4      150          2016-04-06 08:30:27 PM

Now what I want is I want to count the orders that are placed on each day, So the output should be:

count  date
  1    2016-04-04 // For ORD-1
  1    2016-04-05 // For ORD-2
  2    2016-04-06 // For ORD-3 and ORD-4

The code that I tried so far:

$ordersList = Order::latest();

$ordersListDate = $ordersList->selectRaw('date(created_at) as date')
                  ->groupBy('date')->get()
                  ->lists('date')->toArray();

$ordersListCount = $ordersList->select([
    DB::raw('DATE(created_at) AS date'),
    DB::raw('COUNT(code) AS count')
])->groupBy('date')->get()->lists('count')->toArray();

The above controller gives when I do dd($ordersListCount):

array:2 [▼
  0 => "2"
  1 => "1"
  2 => "5"
]

I am scratching my head since long time and couldn't get this done. I know there must be silly thing that I must have missed or not considering, but I am still at the learning stage.

Any help is highly appreciated. Thanks.



via Chebli Mohamed

How to load option's id from database in Laravel 5.1

I tried to load my options from database, my value set correctly but id loaded incorrect :

Controller :

    $country_list = contry::lists('name','id');
    $country_list = array_merge(array('0' => 'Please Select...'),   $country_list->toArray());

View :

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

Database :

"1"=>"USA"
"2"=>"IRAN"
--> "5"=>"ENGLAND" <--

Load in browser :

"0"=>"Please Select"
"1"=>"USA"
"2"=>"IRAN"
--> "3"=>"ENGLAND" <--

I need option id same to id column in database



via Chebli Mohamed

How to display validation errors next to related input field (not as a list) in Laravel 5?

Default solution is trivial:

@if (count($errors) > 0)
<ul id="login-validation-errors" class="validation-errors">
    @foreach ($errors->all() as $error)
    <li class="validation-error-item"></li>
    @endforeach
</ul>
@endif

and I can include errors.blade.php anywhere.

Is there anyway to extract each element and display it next to input field that holds failed value?

I assume that would require to define a lot of conditional statements next to each input. Am I right? How to sort this problem? Could you give any examples?

Thanks.



via Chebli Mohamed

mardi 26 avril 2016

Laravel 5.1: Call to undefined method Illuminate\Database\Query\Builder::fill()

Following much discussion and failed attempts

I need help filling an eloquent model

Also had a probelm with guarding http://ift.tt/241xz8k Which i overcame with protected $guarded = ['id'];

Profile model

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

User Model

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

Controller

public function update(Request $request, $id)
{
    $user = User::with('profile')->findOrFail($id);

    $input = $request->all();


    if(is_null($user->profile)){
        $profile = new Profile($input['profile']);
        $user->profile()->save($profile);
    alert()->warning('New profile creation attempt!');

    }else{
        // $user->profile()->fill($input['profile'])->save();
        $user->profile->title = $input['profile']['title'];
        $user->profile->facebook_username = $input['profile']['facebook_username'];
        $user->profile->meetup_user_id = $input['profile']['meetup_user_id'];
        $user->profile->save();
        // dump($input['profile']['title']);
        // dump($user->profile->title);
        //Unless it fails silently like before.
    alert()->success('Profile Saved!');
    }

    return redirect()->route('admin.users.edit', [$id]);
}

Notice how I am manually filling, this is not ideal obviously. this is the result i am trying to achieve



via Chebli Mohamed

Laravel 5.1: Auth::logout() is not working and Target [Illuminate\Contracts\Auth\Registrar] is not instantiable error

I'm new in laravel and I try to build a simple Authentication. all the things works fine except when using AuthController's action to log out, it just simply doesn't work. I have a nav bar which checks for Auth::check() and it doesn't change after calling the log out action and it stocks in home page. but after making few changes like deleting this manual logout code:

public function logout()
    {
        Auth::logout();
        Session::flush();
        return redirect()->intended('login');
    }

and changing the rout from this:

Route::get('logout', 'SessionsController@logout');

to this:

Route::get('auth/logout', 'Auth\AuthController@logout');

it throws this error:

BindingResolutionException in Container.php line 749: Target [Illuminate\Contracts\Auth\Registrar] is not instantiable. 

I have this route inside the routes.php file:

Route::get('auth/logout', 'Auth\AuthController@logout');

and my AuthController is the controller that laravel providing us.

my SessionsController that handled logout before the changes but actually not work either is:

<?php namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class SessionsController extends Controller
{
    /**
     * Create a new sessions controller instance.
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Show the login page.
     *
     * @return \Response
     */
    public function login()
    {
        return view('auth.login');
    }

    /**
     * Perform the login.
     *
     * @param  Request  $request
     * @return \Redirect
     */
    public function postLogin(Request $request)
    {
        $this->validate($request, ['username' => 'required|exists:users', 'password' => 'required']);

        if ($this->signIn($request)) {
            flash('Welcome back!');

            return redirect()->intended('dashboard');

        }

        flash('Could not sign you in.');

        return redirect()->back();
    }

    /**
     * Destroy the user's current session.
     *
     * @return \Redirect
     */
    public function logout()
    {
        Auth::logout();
        Session::flush();
        return redirect()->intended('login');
    }

    /**
     * Attempt to sign in the user.
     *
     * @param  Request $request
     * @return boolean
     */
    protected function signIn(Request $request)
    {
        return Auth::attempt($this->getCredentials($request), $request->has('remember'));
    }

    /**
     * Get the login credentials and requirements.
     *
     * @param  Request $request
     * @return array
     */
    protected function getCredentials(Request $request)
    {
        return [
            'username' => $request->input('username'),
            'password' => $request->input('password'),
            'verified' => true
        ];
    }


}

This project has deadline so please help me as soon as possible. Any help would be appreciated.



via Chebli Mohamed

Multi Subdomain - Muti Site with Laravel 5

I would like to create a site that has multiple subdomains, each subdomain is an integral independent Laravel application. There is only one folder for the site.

Demontration

www.example.com (the main website)
blog.example.com (An independent blog)
music.example.com (Application of Independent Music)



via Chebli Mohamed

Sendgrid and laravel 5 mail send and receive

I'm currently building a new version of an older website of mine and I'm trying to make a function that allowes users of mine to receive and send emails via that application. So they are be able to log in and send e-mails to another e-mail adress. Also if I sent an email to my domain I want to be able to receive the mail and have a catchall option. I'm currently using Laravel 5.1 and SendGrid.

I really don't know how to receive e-mails. The sending works.



via Chebli Mohamed

API testing in Travis-CI 404 not found

I am trying to setup API Testing in Laravel. We are using travis to automate the build and deploy process. I have tried many different things and up to this point I know that Laravel routing on the travis server does not work.

When the API test attempts to hit an endpoint it always returns 404 not found. I have tried adding "php artisan serve --port=80" to my scripts but it just holds the terminal window and does not continue the rest of the build. The only other option I have considered is to try and point all API calls to the actual URL rather than the masked one so something like ".php?route=something" in plain PHP terms.

I also stumbled upon this post if it helps anyone help me: http://ift.tt/1Syts8W.

I've exhausted all of my options with this one and really need to get this working as it's on a very large project of mine. Any ideas would be greatly appreciated! I have listed one of my tests below.

function it_creates_a_thread()
    {
        $thread = factory(\App\Models\Forum\Thread::class)->make();
        $thread->body = 'Testing';

        $this->authUserPost($this->apiForumResource . '/thread', ['thread' => $thread->toArray()])
            ->seeInDatabase('forum_threads', ['title' => $thread->title])
            ->seeInDatabase('forum_posts', ['body' => $thread->body])
            ->seeJsonContains(['title' => $thread->title]);
    }



via Chebli Mohamed

Laravel 5.1 Custom Parameter on Custom Exception

I am trying to create a custom exception with a custom parameter in it. I feel like I am doing something wrong here. Basically I would like to handle the exception in Laravel's exception handling file but I need extra data with the exception to know things like who caused the exception. This is what I have so far...

<?php

namespace App\Exceptions;

use Exception;

class ApiException extends \Exception
{
    public $userId;

    public function __construct($userId, $message, $code, Exception $previous)
    {
        parent::__construct($message, $code, $previous);
        $this->userId = $userId;
    }

}

The idea here was to pass the userId into the exception so I can access it later. But I am having a problem. In this case, I don't know what to pass in as the "$previous" variable...

throw new ApiException($user->id, 'im testing', 200, $previous);

Any help would be greatly appreciated.



via Chebli Mohamed

Execute a where condition when search key is not null in Laravel query

I would like to run where condition on a select query only when the search key is not empty. If the search key is empty skip that where condition. This is my code,

$users =  User::orderBy('id','asc')
            ->join('agents', 'users.id', '=', 'agents.user_id')
            ->select('users.id', 'users.first_name', 'users.last_name', 'users.email')

            ->where('agents.category', 'like', '%'.$category.'%')

            ->orWhere('agents.location', 'like', '%'.$operation.'%')
            ->get();

In this query if the variable $category is empty no need to run that where condition. and $operation is null what where condition need to be skip. How to solve this issue ?



via Chebli Mohamed

lundi 25 avril 2016

How to remove Serverfireteam Panel from Laravel 5.1

I have tried to remove the serverfireteam/panel from composer.json and i am unable to remove it successfully from my site.

I removed the "serverfireteam/panel": "1.3.*" from composer.json and ran composer update and it is not getting any errors when i give update but to the surprise when i view my site it shows out error like this.

My COMPOSER.JSON file is like this:

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*",
        "doctrine/dbal": "v2.4.2",
        "swiftmailer/swiftmailer": "^5.4",
        "guzzlehttp/guzzle": "~5.3|~6.0",       
        "chrisbjr/api-guard": "^2.3",
        "serverfireteam/panel": "1.3.*",
        "laravel/socialite": "^2.0"

    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1"
    },
    "autoload": {
        "files": [
            "app/Http/helpers.php",
            "app/Support/helpers.php"
        ],
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "pre-update-cmd": [
            "php artisan clear-compiled"
        ],
        "post-update-cmd": [
            "php artisan optimize"
        ],
        "post-root-package-install": [
            "php -r \"copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    }
}

Fatal error: Uncaught ReflectionException: Class log does not exist in /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Container/Container.php:741 Stack trace: #0 /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Container/Container.php(741): ReflectionClass->__construct('log') #1 /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Container/Container.php(631): Illuminate\Container\Container->build('log', Array) #2 /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(674): Illuminate\Container\Container->make('log', Array) #3 /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Container/Container.php(842): Illuminate\Foundation\Application->make('log') #4 /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Container/Container.php(805): Illuminate\Container\Container->resolveClass(Object(ReflectionParameter)) > #5 /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Container/Container.php(774): Il in /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 741

Could anyone help me how to get rid out of this error.



via Chebli Mohamed

Fatal Error Laravel: Uncaught ReflectionException when i view my Site

I have the following error when i view my site.

My Error:

Fatal error: Uncaught ReflectionException: Class log does not exist in /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Container/Container.php:741> Stack trace: #0 /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Container/Container.php(741): ReflectionClass->__construct('log') #1 /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Container/Container.php(631): Illuminate\Container\Container->build('log', Array) #2 /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(674): Illuminate\Container\Container->make('log', Array) #3 /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Container/Container.php(842): Illuminate\Foundation\Application->make('log') #4 /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Container/Container.php(805): Illuminate\Container\Container->resolveClass(Object(ReflectionParameter)) > #5 /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Container/Container.php(774): Il in /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 741

My Composer.json file is like this

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*",
        "doctrine/dbal": "v2.4.2",
        "swiftmailer/swiftmailer": "^5.4",
        "guzzlehttp/guzzle": "~5.3|~6.0",       
        "chrisbjr/api-guard": "^2.3",
        "serverfireteam/panel": "1.3.*",
        "laravel/socialite": "^2.0"

    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1"
    },
    "autoload": {
        "files": [
            "app/Http/helpers.php",
            "app/Support/helpers.php"
        ],
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "pre-update-cmd": [
            "php artisan clear-compiled"
        ],
        "post-update-cmd": [
            "php artisan optimize"
        ],
        "post-root-package-install": [
            "php -r \"copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    }
}

Anyone help me how to get rid of this error and view my site successfully.



via Chebli Mohamed

Language Translation popup is missing on DOM ready in browser: Laravel 5.2

I have below code in my controller.

public function AllCountries() {
    $Countries = (new \App\DataAccess\CountryData())->GetAllCountries();
    app()->setLocale('fr');
    return view('Country.List')->with('Countries', $Countries->getData()->CountryList);
}

Definition of method to fetch data is below.

public function GetAllCountries() {
    return response()->json(['CountryList' => \App\Models\CountryModel::all()]);
}

In English language file I have below code.

return [
    'CountryName' => "E Country"
];

In French language file I have below code.

return [
    'CountryName' => "F Country"
];

In View file I have below code.

{!! trans('CountriesList.CountryName') !!}

Normally when we see websites which is not a default language set in our browser. We see a notification to translate the page on Page load. See the screenshot below.

enter image description here

But this does not come on my side. Although I can see French language but Translation notification is not coming so that I can translate it in English. Why?



via Chebli Mohamed

Eloquent - where has pivot users orWhere has none

I'm trying to write a function that will get all "buckets" that are assigned to the auth'd user and/or buckets that have NO USERS assigned.

Relations and such, work as they should. Unless I'm missing something?

How can I get all buckets user is assigned too - and also include buckets where no users (including the auth user) are assigned.

  1. Buckets user is assigned to
  2. Buckets where NO users have been assigned. i.e. pivot table contains no rows for bucket, etc.

My issue very likely stems from the orWhere query...

$buckets = Team::currentTeam()->buckets()->with('user')->whereHas('user', function($query) {
    $query->where('user_id', Auth::user()->id)
    ->orWhere('user_id', function() {
        $query->count();
    }, '<', 0);
})->get();



via Chebli Mohamed

Else Part is not executing even when condition is false Laravel 5.2

I am working on a Web application where i am searching for student result.By entering student roll no i am getting his data from Database.I have Student Model and Students controller , i am getting input from form and field name = keyword . I am comparing $rollno and the keyword it is working perfect but the else part just executes when i enter roll no 0 , without zero whatever i enter it show me the empty view and else part is not executing.

Search function is in Students Controller

public function search()
        {
            $keyword = Input::get('keyword');
            $rollno = Student::find($keyword);
            if($rollno = $keyword){
                return View::make('results.single')
                ->with('search',Student::where('rollno',$keyword)
                ->get())->with('keyword',$keyword);
            }else{
                return 'Nothing Found';
            }
}



via Chebli Mohamed

Redirect users to the log-in page if the session timeout in Laravel 5

I'm trying to redirect my users to the log-in page if the session timeout.

Here is my route

Route::get('/',['as' => 'login', 'uses'=>'AuthController@getSignIn']);

I've tried adding

    if ( $e instanceof \Illuminate\Session\TokenMismatchException ) {
        return redirect()->route('login');
    }

in render() in app/Exceptions/Handler.php

    public function render($request, Exception $e)
    {
        if ($e instanceof ModelNotFoundException) {
            $e = new NotFoundHttpException($e->getMessage(), $e);
        }

        if ( $e instanceof \Illuminate\Session\TokenMismatchException ) {
            return redirect()->route('login');
        }

        return parent::render($request, $e);
    }

That doesn't seem to take effect.

How do I implement this in Laravel ?

Any suggestions on this will be much helps !



via Chebli Mohamed

How to format a multidimensional/nested array so it only returns the integer and not the column heading?

Im trying to create a nested array when retrieving data from a mysql database that looks like this:

array:2 [▼
  0 => array:3 [▼
    "screen_name" => "Audi"
    "id" => "A1"
    0 => array:3 [▼
      0 => 331
      1 => 350
      2 => 400
    ]
  ]
  1 => array:3 [▼
    "screen_name" => "BMW"
    "id" => "X2"
    0 => array:1 [▼
      0 => 1500
    ]
  ]
]

Currently my array returns data in this format:

array:2 [▼
  0 => array:2 [▼
    "screen_name" => "Audi",
    "id" => "A1",
    0 => array:3 [▼
      0 => {#247 ▼
        +"followers_count": "331"
      }
      1 => {#248 ▼
        +"followers_count": "350"
      }
      2 => {#249 ▼
        +"followers_count": "400"
      }
    ]
  ]
  1 => array:2 [▼
    "screen_name" => "BMW",
    "id" => "X2",
    0 => array:1 [▼
      0 => {#250 ▼
        +"followers_count": "1500"
      }
    ]
  ]
]

Very similar but I need to remove the +"followers_count" in the nested part of the array and only return the integer.

My query is:

$users = DB::table('users')->distinct('social_id')->get();
foreach ($users as $user)
{
    $user_followers = DB::table('user_followers')->where('social_id', $user->social_id)->select('followers_count')->get();
    $records[] = array(
                                                                  'screen_name'   => $user->screen_name,
                                                                  $user_followers,
    );
}

How would I go about stripping out the +"followers_count" in the nested array and just return the integer.

Note: Im using Laravel 5.1 and mysql



via Chebli Mohamed

Laravel 5.1 Foreign Key Trouble

I have some trouble getting the foreign key.

My Migrations looks like this (shortened them):

    <?php

    class CreateProductsTable extends Migration
    {
        public function up()
        {


    Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('email');
            $table->string('title');
            $table->string('filename');
            $table->integer('number_of_chapters');
            $table->text('input_mpg');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop('products');
    }
}

<?php

    class CreateChaptersTable extends Migration
    {

        public function up()
        {
            Schema::create('chapters', function (Blueprint $table) {
                $table->increments('id');
                $table->integer('product_id')->unsigned();   
                $table->time('input-chapter-start1');
                $table->time('input-chapter-end1');
                $table->timestamps();

            });

            Schema::table('chapters', function($table) {
                $table->foreign('product_id')->references('id')->on('products');
            });
        }

        public function down()
        {
            Schema::drop('chapters');
        }
    }

And my 2 Model like this:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Chapters extends Model
{

    protected $table = 'chapters';

    protected $fillable = ['input-chapter-start1', 'input-chapter-end1'];

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

}
<?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Product extends Model
    {

        protected $table = 'products';

        protected $fillable = ['email', 'title', 'filename', 'inputMpg', 'number_of_chapters'];

        public static $rules = [
            'email'                => 'required|email|max:50',
            'title'                => 'required|max:50',
            'filename'             => 'required|max:50',
            'input_mpg'            => 'required'
        ];

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

    }

And just save it like this in my Controller

$product->save();
$Chapters->save();

And get following error:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (generator.chapters, CONSTRAINT chapters_product_id_foreign FOREIGN KEY (product_id) REFERENCES products (id)) (SQL: insert into chapters (input-chapter-start1, input-chapter-end1, updated_at, created_at) values (12:12:12, 12:12:12, 2016-04-25 11:41:31, 2016-04-25 11:41:31))



via Chebli Mohamed

Retrieving data from ajax call in controller

I have an ajax call that is sending some IDs to one of my controllers.

The jQuery that is running to do this is basically searching for elements that have an ID like notification-id- and then grabbing the IDs and storing them in a JavaScript variable.

When I alert() or console.log() this variable it prints out values like 1,2 for two notifications that I have on the page notification-id-1 and notification-id-2.

For my ajax call, I am simply doing the below:

$.ajax({
  url: "",
  method: "POST",
  data: notifications, // Let jQuery handle packing the data for you
  success: function(response) {
       // The data was sent successfully and the server has responded (may have failed server side)
   alert(notifications);
  },
  error: function(xhr, textStatus, errorThrown) {
      // AJAX (sending data) failed
  },
  complete: function() {
      // Runs at the end (after success or error) and always runs
  }
});

I'm trying to test what my controller is receiving by doing dd($request->all()); however that is just returning:

array:1 [
  "undefined" => ""
]

(The ajax call does run successfully)

How can I retrieve the ID values that are being sent in this ajax call inside my controller?



via Chebli Mohamed

Laravel 5.1 eloquent Unsupported operand types

I am trying to get query result to array and show them in select element. When I hardcode it like this, it works fine:

$categories = ['Editorial', 'Product test', 'News', 'Feature'];
$categories = ['select_category']+$categories;  

return view('admin.articles.create', compact('categories'));

But when I try to get categories form DB, I get the above mentioned error.

$categories = Category::all();
$categories = ['select_category']+$categories;

return view('admin.articles.create', compact('categories'));



via Chebli Mohamed

Marking notifications as read

I recently came across a tutorial on how to implement notifications rather easily in to a Laravel application, and so I followed Part 1 and Part 2 of these tutorials and have notifications working - which is great.

What the tutorials don't cover is a good system for marking these as read, as I guess this all depends on how you want to do it.

For simplicity sake, when the user clicks on my notification banner, I want to mark any new notifications in there as read - I'm just not certain how to do this.

I think this could be achieved with some jQuery and fetching the id's of the element that all start with notification- (e.g notification-1, notification-2).

This is what the notification part of my view looks like:

<!-- Notifications Menu -->
<li class="dropdown notifications-menu">
            <!-- Menu toggle button -->
            <a href="#" class="dropdown-toggle" data-toggle="dropdown">
              <i class="fa fa-bell-o"></i>
              <span class="label label-warning">@if (Auth::user()->notifications()->unread()->count() > 0)
                  
                @endif</span>
            </a>
            <ul class="dropdown-menu">
              <li class="header">You have  new notifications</li>
              <li>
                <!-- Inner Menu: contains the notifications -->
                <ul class="menu">
                  <li><!-- start notification -->
                  @if (Auth::user()->notifications()->unread()->count() == 0)
                    <a href="#">
                      <i class="fa fa-bullhorn text-aqua"></i> Start using the site to get notifications.
                    </a>
                  @else
                    @foreach (Auth::user()->notifications()->unread()->get() as $notification)
                      <a href="#" id="notification-">
                        <i class="fa fa-bullhorn text-green"></i> 
                      </a>
                    @endforeach
                  @endif
                  </li><!-- end notification -->
                </ul>
              </li>
              
            </ul>
          </li>

This part holds the count of the notifications and displays this to the user, having nothing inside the span will mean that no notification indicator is shown:

<span class="label label-warning">
    @if (Auth::user()->notifications()->unread()->count() > 0)
        
    @endif
</span>

And each notification is populated, using the below:

@foreach (Auth::user()->notifications()->unread()->get() as $notification)
    <a href="#" id="notification-">
        <i class="fa fa-bullhorn text-green"></i> 
        
    </a>
@endforeach

What is the best way to grab the displayed notification IDs, post them to a route (so they can be marked as read) and clear the span that shows the notification count?

I can figure out the ajax call, I just need help getting started - specifically with how to grab all the IDs and clearing the span.



via Chebli Mohamed

samedi 23 avril 2016

Creating Simple Quiz Logic in Laravel

These are my Schema Tables

Schema::create('question', function(Blueprint $table) {
            $table->increments('id');
            $table->text('title');
            $table->string('hint')->nullable();
            $table->text('explanation')->nullable();
            $table->string('referencematerial')->nullable();
            $table->string('imagepath')->nullable();
            $table->boolean('published')->default(1);
            $table->timestamps();
            $table->softDeletes();
        });

Schema::create('answers', function(Blueprint $table) {
            $table->increments('id');
            $table->string('text');
            $table->boolean('iscorrect')->nullable();
            $table->timestamps();
        });

Here is my Classes for Question and Answer.

class Answer extends Model
{
    protected $table = 'answer';

    public $timestamps = true;

    protected $fillable = array('text', 'iscorrect');

    public function Question()
    {
        return $this->belongsTo('Question');
    }

}

class Question extends Model
{
    protected $table = 'question';
    public $timestamps = true;

    protected $dates = ['deleted_at'];
    protected $fillable = array('title', 'hint', 'explanation', 'referencematerial', 'imagepath', 'published');


    public function Answer()
    {
        return $this->hasMany('Answer');
    }

}

My QuizController

public function index()
{
    $questions = Question::with('answers')->get();
    return $questions;
}

BadMethodCallException in Builder.php line 2251:
Call to undefined method Illuminate\Database\Query\Builder::answers()

I have been trying to load the questions and answers on the page. It keeps giving me query builder error. Please feel free to chime into it.



via Chebli Mohamed

laravel 5.1 validation mimes error doesn`t display

hi I have this validation

 $this->validate($request, [
     'image' => 'required|mimes:jpeg,bmp,png',
 ]);

error for required its Ok . but when your image extension in not jpeg,bmp,png i haven`t error



via Chebli Mohamed

How to change value of a request parameter in laravel 5.1

I need to change value of my request parameter like this .

$request->name = "My Value!"

i use this code but does not work .

$request->offsetSet('img', $img);



via Chebli Mohamed

laravel 5.1 how to use Storage->get() in view

I need load my files in storage/app/folder/file.ex in view and I use Storage . but have problem with image source. enter image description here

<img src="" >

how can i fix this ?



via Chebli Mohamed

Paymentwall fingerprint not getting generated

I was trying to integrate the paymentwall api in my laravel 5.1 application, unfortunately i am not getting the fingerprint that is generated through jquery. I tried passing 'browser_ip' = $_SERVER['REMOTE_ADDR'] and 'browser_domain' = $_SERVER['HTTP_HOST'] but its returning an error. I tried passing ip's other than $_SERVER['REMOTE_ADDR'] , that too didnt work. Any help would be appreciated.

regards,



via Chebli Mohamed

vendredi 22 avril 2016

Laravel 5.1 - add missing data to response

I have this function to get all max-offers from maxoffers table:

public function maxoffers($id)
    {

        $offers = Maxoffer::where('article_id', $id)->latest()->get(['id', 'price', 'start', 'user_id']);

        return $offers;
    }

and I get this:

[{"id":121,"price":67,"start":"Sat, 23 Apr 2016 00:00:00 +0000","user_id":8},{"id":114,"price":45,"start":"Sun, 08 May 2016 00:00:00 +0000","user_id":9},{"id":113,"price":53,"start":"Sun, 24 Apr 2016 00:00:00 +0000","user_id":8},{"id":111,"price":55,"start":"Wed, 01 Jun 2016 00:00:00 +0000","user_id":11},{"id":110,"price":53,"start":"Fri, 03 Jun 2016 00:00:00 +0000","user_id":8},{"id":107,"price":53,"start":"Wed, 03 Aug 2016 00:00:00 +0000","user_id":8},{"id":106,"price":53,"start":"Mon, 01 Aug 2016 00:00:00 +0000","user_id":8},{"id":105,"price":53,"start":"Tue, 16 Aug 2016 00:00:00 +0000","user_id":8},{"id":104,"price":55,"start":"Thu, 21 Apr 2016 00:00:00 +0000","user_id":11},{"id":101,"price":57,"start":"Wed, 17 Aug 2016 00:00:00 +0000","user_id":8}]

Now i have also:

$start = 'Sun, 03 Apr 2016 00:00:00';
$end = 'Sat, 23 Sep 2016 00:00:01';

How I can go day by day throuth $offers from $start date to $end date and if there is no date for that day to add into $offers new object with data:

{"title":,"price":100,"start":"DATE_WHICH_NOT_EXCIST INTO_OFFERS","user_id":8}

So how I can go throuth $offers and if there is not some date in period from $start to $end then to add new object to json?

So if some date bettween start and end dont excist then add new object... How I can make it possible?

better exaplanation: With $offers I get json with dates but not all dates. So I need to get for all dates between start and end if not alredy exict into offers



via Chebli Mohamed

Laravel 5.1 - Dreamhost VPS - Always getting 404 exception

I have been breaking my head for the last two days now and still don't have a solution. All routes in my Laravel 5.1 are throwing a NotFoundHttpException.

My folder structure looks like this:

enter image description here

Some additional info

  • Both example.com and abc.example.com have web directory set to /home/username/http://ift.tt/1XNsERo
  • I have a .htaccess file inside the public folder which looks like

    Options -MultiViews

    RewriteEngine On
    
    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]
    
    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
    
    

As Image: enter image description here

  • Debugbar is showing the following error:

enter image description here

Any help will be highly appreciated. I have tried almost all solutions found on Google. None worked.



via Chebli Mohamed

Laravel Excel - Ajax and JSON

Hey I am trying to generate a .xls file in my Single-page application. The data I have is an array of JSON objects. Now, the problem is that when I do an ajax call with the json data to my controller:

$.post('/api/exportJSON', {data:jsonData, exportOptions: eOptions}, function(res){
    console.log(res);
}); 

It returns:

��ࡱ��������������������

This is my route:

Route::group(array('prefix' => 'api'), function() {
    Route::any('/exportJSON', 'ApiController@exportJSON');
});

This is my controller method:

 public function exportJSON(){

    $filename = 'Test list';
    $filetype = 'xls';

    Excel::create($filename, function($excel) {

        $excel->setTitle('test')
              ->setCreator(Auth::user()->name)
              ->setDescription('test')
              ->setCompany('test')
              ->sheet('test', function($sheet) {

                    $sheet->setOrientation('landscape');

                });


        })->store($filetype)->export($filetype);
}

How should I do it? Btw it's not a must to do an ajax call, I can also do with a form, but I must be able to send parameter (the json list and options) to my export method. I also tried to make a post form like so in my view:

{!! Form::open(array('url' => 'api/exportJSON', 'method' => 'post', 'class' => 'form')) !!}

//insert hidden fields with the options here...

{!! Form::submit('Download xls', array('class'=>'btn btn--green')) !!}

{!! Form::close() !!}

But that doesn't work, i get a page not found error..

BUT when i browse to localhost/api/exportJSON it automatically downloads the .xls correctly and when i make a link <a href="/api/exportJSON">Download</a> in my view, when i click Download it downloads the .xls file but how can i send parameters? Can i add a huge list as GET params in that url?

Any ideas?



via Chebli Mohamed

printing all running session variable in laravel 5.1

How do I print all running session variable in Laravel 5.1?

I want to print all the running session variable. Currently I can retrieve single running session for given value but don't know the function for print all at one time with one function something like





via Chebli Mohamed

Laravel 5.1 deleting sub-relationship data when row is deleted

I have an application in Laravel 5.1 where the following tables are setup;

  • timesheet
  • row
  • day_total
  • segment_totals

Rows belong to timesheets. Day totals belong to timesheets. Segment totals belong to rows.

When a timesheet is deleted, I also want it to delete the rows from row, day_total and segment_total as well as the row from timesheet table itself.

I hav setup the following boot method in my timesheet model;

/**
 * Boot the model.
 *
 */
public static function boot()
{
    parent::boot();

    static::deleting(function($timesheet)
    {
        $timesheet->row()->delete();
        $timesheet->dayTotal()->delete();
    });
}

I have setup the following in the row model;

/**
 * Boot the model.
 *
 */
public static function boot()
{
    parent::boot();

    static::deleting(function($row)
    {
        $row->day()->delete();
        $row->segmentTotal()->delete();
    });
}

When the timesheet is deleted, the row and dayTotal rows are deleted, but the day and segmentTotals do not get deleted. How can I make Laravel fire the delete on the row model?



via Chebli Mohamed

Laravel Foreing Key Integrity constraint violation

I have two tables in Laravel 5.1 which I created with the following migrations:

class CreateProductsTable extends Migration
{

    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('email');
            $table->integer('number_of_chapters');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop('products');
    }
}

and the second one:

class CreateChaptersTable extends Migration
{

    public function up()
    {
        Schema::create('chapters', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('chapter_id')->unsigned();
            $table->time('input-chapter-start');
            $table->time('input-chapter-end');
            $table->timestamps();
        });

        Schema::table('chapters', function($table) {
            $table->foreign('chapter_id')->references('id')->on('products');
        });
    }

    public function down()
    {
        Schema::drop('chapters');
    }
}

My Product Model looks like this:

<?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Product extends Model
    {

        protected $table = 'products';

        protected $fillable = ['email', 'title', input-chapter-start', 'input-chapter-end'];

        public static $rules = [
            'email'                => 'required|email|max:50',
            'title'                => 'required|max:50'
        ];

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

        $Chapters = new Chapters;

    }

And my Chapters Model looks like this:

<?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Chapters extends Model
    {

        protected $table = 'chapters';

        protected $fillable = ['input-chapter-start', 'input-chapter-end'];

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

The problem is now that I do not get any values in my chapters table in my database. How do I manage this?

If I try to save the data in my Controller I get following error message:

QueryException in Connection.php line 651: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (html_gen.chapters, CONSTRAINT chapters_chapter_id_foreign FOREIGN KEY (chapter_id) REFERENCES products (id)) (SQL: insert into chapters (updated_at, created_at) values (2016-04-22 11:32:04, 2016-04-22 11:32:04))



via Chebli Mohamed

How to get last inserted id using Eloquent::insert()

I am inserting bulk insertions in laravel 5 like this:

$data = array(
    array('name'=>'Jack', 'age'=>'24'),
    array('name'=>'Tom', 'age'=>'37'),
    //...
);

Users::insert($data);

Any idea how to get last inserted id?



via Chebli Mohamed

jeudi 21 avril 2016

Laravel 5 and Cloudflare SSL

Well, today the first time I decided to use ssl on my web project. Firstly, I configured my domain in cloudflare.com. Then I turned on page rules in cloudflare, to automatic redirect the website to https.

http://*example.com/*

To make sure that it works, i added simple index.php to the public_html and it worked. I mean, when I entered to the web site, https was active and the site displayed me the famous word: "Hello World"

After that I uploaded my Laravel project to the web server and configured virtual host. I use nginx server.

server {
        listen 80;

        root /home/user/www/http://ift.tt/1SV0Oyb;
        index index.php index.html index.htm;

        server_name example.com

        location / {
                try_files $uri $uri/ =404;
        }

        error_page 404 /404.html;
        error_page 500 502 503 504 /50x.html;

        location = /50x.html {
                root /usr/share/nginx/html;
        }

        location ~ \.php$ {
                try_files $uri =404;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_nam$
                include fastcgi_params;
        }
}

Well, when I enter to the website with https, Laravel routes don't work. Also, my css and js files weren't read by server.

Then I turned off page rules from cloudflare, site worked good with http.

I tried to configure the server with 443, used ssl on command, but wasn't any result.

Also, I found this link about cloudflare with laravel 5. But not sure, this is that, what I want.

Laravel Cloudflare

Any help, would appreciated.



via Chebli Mohamed

Laravel query with max and group by

I need to create a select query in Laravel 5.1 which I will have no problems creating via regular SQL and I am wondering if you could help me to write it in Laravel.

I created this query that gets all Users that have a truck, trailer and delivery_date equals a particular date (comes from $week_array). It is working, but it is missing some components

$RS = $this->instance->user()
        ->with(['driver.delivery' => function($query) use ($week_array) {
           $query->where('delivery_date', [Carbon\Carbon::parse($week_array['date'])->toDateTimeString()]);
             }])
        ->with(['driver.trailer', 'driver.truck', 'driver.trailer.trailerType'])->get();

I need to exclude those drivers that have MAX delivery date which equals or greater than selected delivery date in the query above. This is the normal query that I need to plug-in to laravel.

select driver_id, max(DATE(delivery_date)) as delivery_date 
  FROM deliveries 
WHERE instance_id = ? 
GROUP by driver_id



via Chebli Mohamed

HTTPS Nginx Configuration for Laravel 5

I currently have an HTTP laravel 5 app. The app is functioning fine. I'm trying to move to HTTPS. I already bough the cert, and here is my

Nginx Configuration

#HTTPS
server {

        listen 443 ssl;
        server_name my-site.com;
        ssl on;
        ssl_certificate /etc/ssl/my-site.crt;
        ssl_certificate_key /etc/ssl/my-site.key;

        root /usr/share/nginx/my-app/public;
        index index.php index.html index.htm;

        location / {

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

        location ~ \.php?$ {

                try_files $uri =404;
                include fastcgi_params;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_read_timeout 300;
                fastcgi_intercept_errors on;
                fastcgi_split_path_info ^(.+\.php)(.*)$;
                #Prevent version info leakage
                fastcgi_hide_header X-Powered-By;
                proxy_read_timeout 300;

        }

}

#HTTP
server {

        listen 80;
        server_name my-site.com;
        rewrite ^/.*$ https://$host$request_uri? permanent;
        return 301 https://$host$request_uri;

        #More Settings ..

        #root /usr/share/nginx/my-app/public;
        #index index.php index.html index.htm;

        #location / {

                #try_files $uri/ $uri /index.php?$query_string;
        #}

        #location ~ \.php?$ {

                #try_files $uri =404;
                #include fastcgi_params;
                #fastcgi_pass 127.0.0.1:9000;
                #fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                #fastcgi_read_timeout 300;
                #fastcgi_intercept_errors on;
                #fastcgi_split_path_info ^(.+\.php)(.*)$;
                ##Prevent version info leakage
                #fastcgi_hide_header X-Powered-By;
                #proxy_read_timeout 300;

        #}

}


Now with this settings, I am one step closer,

I can see that when I go to : my-site.com

It redirect to https://my-site.com

But however, I won't be able to log-in at all. It kept bouncing me back out.


Do I need to adjust anything in my Laravel route ?

How do I prevent this from happening ?

How do you guys host your Laravel app in HTTPS ?


Any hints / suggestions on this will be much appreciated !



via Chebli Mohamed

[Unable to find the socket transport "TLS" - did you forget to enable it when you configured PHP? #32673]

I'm facing the following message when sending email through Zoho SMTP server.

[Unable to find the socket transport "TLS" - did you forget to enable it when you configured PHP? #32673]

I tried looking for opennssl support on my PHP installation and it seems everything is OK.

My phpInfo() says that the TLS stream are registered and openssl extension enabled.

I'm using Laravel 5.1 on a ubuntu server 14.04 on Digital Ocean and PHP 5.6.20. I google for a solution but I just found answers for Windows OS.



via Chebli Mohamed

Generating Unique Receipt Codes in Laravel

Hello in my laravel application I have a function that generates a unique receipt code whenever a customer completes a transaction.

This is the format of the code: 1. 4 Digit Identifier of Store eg. ABCD 2. Type or Category of item purchased. eg. E for electronics, T for toys 3. Special secret two digit code eg. can be between 01 and 10. 4. Date in really short format. eg. 31J16 for 31st January, 2016 5. Four digit code for customers to use for support issues or returning an item. eg. 3267. This is randomly generated.

So a sample would look like this: ABCDT0131J163267 Total length is 16 characters.

Now what I want to do is each time a code is generated make sure it does not already exist in my database if yes then it should generate a new one and so on till it comes up with a unique code.

Now my issue is getting an efficient solution t generate unique codes that won't end up looping soo many times like I intend on doing.



via Chebli Mohamed

Best way to manage laravel 5 logs for each event

I wants to logs for each events happened in my website. I would like to know what will be the best way to handle this?

I looked at the packages available but it's not in my requirement.

Let say I wants to record every email activity went through the system plus all insert/update/delete performed by the system user.

I saw EventListener but each time I have to fire an event from the controller I would love if is there any way if I just have to write one time code at somewhere so anytime insert/update/delete happened It will be recorded yes plus emails as well.

Help would be most appreciated.

Thank you.



via Chebli Mohamed

Laravel5.1 Logout when browser is close using javascript

How to detect that browser is close using javascript. I have not found any solutions using laravel. So now I am using jquery ajax request to logout before window is close. For this I am using-

function windowUnloaded() {

    var unloaded = false;
    $(window).on('beforeunload', unload);
    function unload(){      
        if(!unloaded){
            $('body').css('cursor','wait');
            $.ajax({
                type: 'get',
                async: false,
                url: '/logout',
                success:function(){ 
                    unloaded = true; 
                    $('body').css('cursor','default');
                },
                timeout: 5000
            });
        }
    }
}

This works only when I refresh page. But I want it when browser is close. Somebody can tell me from where I am wrong or If there is any other better solution. Thanks in advance.



via Chebli Mohamed

Laravel about Requests

i am new in programing laravel. so here I will not ask about my problems but I am here just want to ask how to use laravel. here I would like to ask how to use:

Determining If an Input Value Is Present in laravel. and what it does?

thanks ^^



via Chebli Mohamed

adding data to @include throws an error

My head is aching as to what is the error in my code.

main.blade.php

Html with angular codes here....
@include('modal-template-common', ['link' => route('client.logout')]

modal-template-common.blade.php

{!! Html::link($link, 'OK', ('class'=>'btn btn-danger')) !!}

Now the problems is whenever I try to render it returns an error of

ErrorException in UrlGenerator.php line 273

angular.js:11607 Error: [$compile:tpload]

any enlightenment would greatly help me.



via Chebli Mohamed