dimanche 31 janvier 2016

Handle Html tags in input area

Need to allow/disallow some certain html tags in js side. Developing a laravel project where in some input box need to consider certain html elements.

Can be done using string replace function but will take much more time to maintain the list of not allowable items.like the following

function escapeHtml(unsafe) {
    return unsafe
         .replace(/&/g, "&")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
 }

Again the allowed html tag list can also be small so if just want to allow
then the unsafe list will be huge.

I can also do it in server side but cant get any proper source for that.

It will be so helpful if someone can just suggest me what would be the best way for maintaining this allow/disallow html tag list?



via Chebli Mohamed

Laravel Shopify API Wrapper, refused the connection

I have a project on building a shopify app through "embedded SDK" The app was installed successfully but it does not redirect back to admin where the app should show the API call result. When I try to access the app that I installed the frame will just display The server refused the connection.

I used the joshrps/laravel-shopify-API-wrapper for my laravel project. This is my controller where I make a request to install the app http://ift.tt/1Tw2ZN3 , this is my redirect uri when the app is successfully installed:

Route::get('shopify',function(){
    $sh = App::make('ShopifyAPI',[
        'API_KEY'=>'a1568bd534e2e7a88b21d693bdc73afe',
        'API_SECRET'=>'b15f951478db59369da196e77ea23fb7',
        'SHOP_DOMAIN'=>'shinobishop.myshopify.com']);
    $code = Input::get('code');
    try`enter code here`
    {
        $accessToken = $sh->getAccessToken($code);
    }
    catch (Exception $e)
    {
        echo '<pre>Error: ' . $e->getMessage() . '</pre>';
    }
));

I hope you can help me with this issue. Its my first time using shopify API on projects.



via Chebli Mohamed

Laravel 5.2 - Class 'GuzzleHttp\Client' not found, live only

I have my config/mail 'driver' set to mandrill, host, port, etc. including in services.php mandrill secret set.

Sending Mail works find locally, but on the live server I get: Class 'GuzzleHttp\Client' not found

I have tried "guzzlehttp/guzzle": "~5.3|~6.0", and then back to "guzzlehttp/guzzle": "~4.0", no luck. I have done composer update, and dump-autoload still no luck on my live server. Been through every other associated Stackoverflow question and still can't resolve.



via Chebli Mohamed

Laravel 5.2 - Staging to Live Server : 500 Internal Server Error

I have a Laravel 5.2 project working fine locally, after uploading to a live server I have a 'laravel' folder in my root directory and public folder under 'public_html/testsite'

My 'index.php' points to the correct '/bootstrap/autoload.php' and '/bootstrap/app.php'

Upon going to my 'url/testsite/' I get a blank page only (was working fine L5.0) firebug shows : 500 Internal Server Error with HTML : Reload the page to get source for...

index.php is loading by testing with die() before any 'require' methods, but after 'require... autoload.php' the die() is not working, however it is successfully calling autoload.php as a die() works within this file.

I'm not sure if this is a .htaccess issue, or maybe I had to set something up in cPanel last time for this folder (I can't remember). I'd appreciate any help!

Please note this Laravel project sits as a test site in a /testsite/ folder along with my current live site files.



via Chebli Mohamed

Using Node, Socket.io, and Redis on a production server?

I am very new to the whole idea of redis and socket.io but I followed this laracast series and I was able to get basic Laravel events to broadcast successfully.

The problem arose when I tried to push my code to a server. First some code:

socket.js

var server = require('http').Server();
var io = require('socket.io')(server);
var Redis = require('ioredis');
var redis = new Redis();

redis.subscribe('test-channel');

redis.on('message', function(channel, message) {
    console.log(message);
    message = JSON.parse(message);

    io.emit(channel + ':' + message.event, message.data);
});

server.listen(3000);

main.blade.php

var socket = io('http://localhost:3000');

// not relevant stuff for using Vue.js

socket.on('test-channel:App\\Events\\EventWasCompleted', function(data) {
    // push stuff to Vue.js
}.bind(this));

routes.php

Route::get('/fire', function() {
    $i = 0;
    while ($i < 10) {
        event(new EventWasCompleted($i); 
        $i++;
    }
    return 'Done';
});

Now what happens is when I am working locally, is that I can visit the main view and hit the /fire route (ex: localhost/fire) and my event is broadcasting correctly and the results are pushed to the main view.

However, when I tried to push to production, I wasn't really sure what I needed to change if anything. I ran node socket.js on the server, and I know that it is working because I can see the results of my event in the console. The issue is that my main view does not properly receive the events. If I hit my local route localhost/fire I do catch the events on my production server. However if I hit productionIp/fire I can't catch the events.

What do I need to change to get this to work?



via Chebli Mohamed

Laravel multiple container bindings of same type

I have over 70 repositories for my models I would like to register a service provider for them. I am using Doctrine2.

Each repository extends DefaultRepository which in turn extends doctrines EntityRepository.

Since EntityRepository needs two parameters in constructor, I need to provide them, e.g.

$this->app->bind(PersonRepository::class, function($app) {
    return new PersonRepository(
        $app['em'],
        $app['em']->getClassMetaData(Person::class)
    );
});

But I would need to do it 70 times...

I could bind doctrines ObjectRepository interface or DefaultRepository class, but since some of the repositories have custom methods, I would need to manually type hint it then e.g. /** @var PersonRepository $person to get correct autocomplete. Which is not something I would like to do.

I didn't manage to get contextual bindings to work either. Even when I tried to bind doctrines EntityRepository.

The only thing that comes to mind now, is using a deferred provider and loading list of all repositories from filesystem (since I want this process to be automatic), then cache them in a file (in all environments except local) and bind them in a loop. But this seems a bit too much work to get this task done.

Is there any easy/preferred way to bind all repositories without writing 70 $this->app->bind lines?



via Chebli Mohamed

NetBeans : giving syntax error in laravel 5.2

Following is the snippet of code from Kernel.php in laravel.

 protected $middleware = [
            \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        ];

Netbeans says

Syntax error
     unexpected:    class
     after: ::
     expected:  identifier

POSSIBLE Syntax Error (check preceding valid syntax error)
 unexpected:

What's going on ? underline on whole line is irritating me.



via Chebli Mohamed

How to assign certain player-models from a user-pool to one of two teams which belong to a match in Laravel?

Imagine a site where you are a registered user with a given rank to calculate your strenght. You would accidentally click a button, which sets yourself free for the app to get matched with other users. Just as strong as you. After that you can choose from a few options and the match will begin. But this is still a dream.

I have:
- working relations: http://ift.tt/1PJVrAq
- groupable users: $users = User::where('queueing', '1')->where('rank', $request->user()->rank)->get();

I need:
- a clue how to go forward!
- where should and how do I exactly have to tell Laravel to create a new Match (1 Match always has 2 Teams, each with 5 Players from a total of 10 Users)

Appflow:
- User wants to play a match > he will create a player(?), which is part of a team in the match. If the match is over, the user hopefully wants another match > he will create a NEW player, in a NEW team and a NEW match. All from zero again.

I think it's something from http://ift.tt/1mH8Zpu, but I keep only seeing trees...

Part of MatchController if needed:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Auth;
use App\User;
use App\Hero;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class MatchController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function showPlayForm()
    {
        $heroes = Hero::all();

        return view('match.play', ['heroes' => $heroes]);
    }

    public function play(Request $request)
    {
        $this->validate($request, [
            'type' => 'required',
            'role' => 'required',
        ]);

        $this->addToQueue($request);

        return redirect('/queue');
    }

    public function showQueue(Request $request)
    {
        $users = User::where('queueing', '1')->where('rank', $request->user()->rank)->get();

        return view('match.queue', ['users' => $users]);
    }

    public function addToQueue($request)
    {
        $user = $request->user();
        $user->queueing = 1;
        $user->save();
    }
}

Would someone kick me in the right way please?



via Chebli Mohamed

Laravel many to many relationship returning unexpected result

I have problems with my many to many relationship returned data. I have 3 tables to define this relationship users, institutes and the pivot table users_institutes. The data in my users_institutes is in the image.

enter image description here

My relationship is defined by the following code.

public function super_user_institutes()
{
    return $this->belongsToMany('App\Institute', 'users_institutes')
        ->wherePivot('role', 'inst_superuser')
        ->orWherePivot('role', 'inst_admin')
        ->orWherePivot('role', 'inst_staff')
        ->withPivot('role');
}

Now, for the user I'm trying to get the relations for has the id 2. So, now if I use

$user->super_user_institutes;

I get the following rows in response: 1, 2, 3, 9, 10, 11, 12 (7 rows).

Where I expect the following rows: 1, 2, 3.

Am I expecting a wrong result? or my relationship definition is wrong?



via Chebli Mohamed

Laravel Blade View Freezing

I am confused. i have tried all workaround. when i load the page it freezes. if i check on chrome task manager memory keeps increasing (200MB+). can someone point me what is the issue in here ?

My Route :

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

My Parent Layout : core.blade.php

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<div id="container">

    @yield('content')

</div>

</body>
</html>

My Index View : index.blade.php

@extends('core')

NOTE : if i remove the extends tag. it runs smoothly.

this is my structure

enter image description here

Can someone point me what is this issue ?



via Chebli Mohamed

Laravel 5.2, three way many too many

I want to do the following.

I have three models: User, Business, Role

They are connected as follows: Users can have many roles, and belong to multiple businesses.

Roles are predefined.

I want that each user can have different roles in different businesses. For example, in business1 the users has role sales manager, but in business2 he has role director. User can have multiple roles on same business.

User model:

public function businesses()
{
    return $this->belongsToMany('App\Business')->withTimestamps();
}

Business model:

   public function users()
    {
        return $this->belongsToMany('App\Business')->withTimestamps();
    }

Pivot table:

    Schema::create('business_user', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->integer('business_id')->unsigned();
        $table->integer('user_id')->unsigned();
        $table->integer('role_id')->unsigned();
    });

I add the User to the Business as:

$user->businesses()->attach($business_id, ['role_id' => $roleId]);

This should add the row in pivot table as: ['1','2','3'].

My questions are:

  • Is this the right way to do this?
  • How do I proceed with detach method?
    $user->businesses()->detach($business_id)->where('role_id',$role_id); This is not the correct syntax but something like this. If the user has two roles in a business (for example: 'director' and 'sales manager') on detach I want to remove just one of the roles (for example: 'director') and not all of them. I believe that running $user->businesses()->detach($business_id); will detach all roles.
  • Is there a way to use the sync() method with this?


via Chebli Mohamed

Class 'App\Http\Controllers\Controller' not found - Laravel 5.2

Hello i am new here but already checked all solutions about my problem here and still didn't fix it :)

I want to create simple app with tutorial in Laravel 5.2, and i can't make my controller to work.

I named my app "test" and here is a code:

PagesController.php :

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

class PagesController extends Controller
{
    public function getAbout(){
         return view('about');   
    }
}

routes.php:

Route::get('about', [
    'as' => 'about',
    'uses' => 'PagesController@getAbout'
]);

And Controller.php (default):

namespace test\Http\Controllers;

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

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

Guys do you see any problem here? My friend has got exactly the same problem... I am sure all files are in correct folders.



via Chebli Mohamed

MethodNotAllowedHttpException error in Laravel 5 using ajax

I am trying to upload an image with ajax and i am getting: Failed to load resource: the server responded with a status of 500 (Internal Server Error). Here is my ajax:

$('document').ready(function() {
    $('#uploadImage').change(function(){
        image = $('#uploadImage').val;
        token = $('#token').val();
        $.ajax ({
            type: 'POST',
            url: '/photo',
            data: { image , token },
            success: function(){

                $('.img-thumbnail').attr("src", 'images/new_image.png');
            }
        })
    })


});

Here is my route: Route::post('/photo', 'ShopsController@uploadPhoto');

This is my controller:

public function uploadPhoto(Request $request)
    {

        //Sets file name according to authenticated shop id
        $imageName = 'new_image.png';

        //Save file to public/images

        $img = Image::make($request->file('image'));
     $img->resize(380, 300)->save('images/' . $imageName, 60);
    }

And this is my form:

<form action="{{ action('ShopsController@store') }}" method="post" enctype="multipart/form-data">
    <input id="token" type="hidden" name="_token" value="{{ csrf_token() }}">
   <input id="uploadImage" class="btn btn-upload" type="file" name="image"> </form>



via Chebli Mohamed

Putting image as submit button Laravel

I can't seem to find a way to put image as submit button in blade, is there a way to do this?

 {!! Form::submit('Search', array('class'=>'btn')) !!}



via Chebli Mohamed

Form with has many relationship

What is the better way to create a model with has many relationship?

For example:

I have two models:

  • Client (id, name, ...)
  • Contact (id, type, value, description)

A client has many Contacts.

Example of create client view: http://ift.tt/1SRReB0

Problems:

  1. how to deal with validations?
  2. if validation fails, going back and fill in the contact with the respective errors?


via Chebli Mohamed

how to add adobe edge content to laravel 5?

my friends my problem is when add "edge content" to my laravel not work for me!! how to play this animation with public DIR ?

AdobeEdge.loadComposition('page1', 'stage', {
scaleToFit: "none",
centerStage: "none",
minW: "1200px",
maxW: "undefined",
width: "100%",
height: "100%"
}, {"dom":{}}, {"dom":{}});



via Chebli Mohamed

Laravel form request not redirecting correctly

I've just updated from laravel 5.1 to 5.2 and my form requests instead of redirecting to $redirect now throws me this error: "HttpResponseException" from here:

 * @param  \Illuminate\Contracts\Validation\Validator  $validator
 * @return mixed
 *
 * @throws \Illuminate\Http\Exception\HttpResponseException
 */
protected function failedValidation(Validator $validator)
{
    throw new HttpResponseException($this->response(
        $this->formatErrors($validator)
    ));

my form request code:

<?php 

namespace App\Http\Requests;

use Auth;

class ArticleEditRequest extends Request
{
    protected $redirect = '/';

    private $rules = ['message' => 'max:128'];

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

    public function authorize() 
    {
        return Auth::check();
    }
}

With laravel 5.1 it would just redirect to '/' with errors that then would be flashed to the user. How do I fix this? I tried overwriting failedValidation to redirect to $redirect, but then after failed validation it would still execute the controller code.



via Chebli Mohamed

Laravel deleting method

I have written the code below in my controller to delete a comment :

public function destroy($ID)
{
    $post = Comment::find($ID);
    $post->delete();
    return redirect()->back();
}

And this is my Route :

Route::delete('/deleteComment/{ID}', 'CommentController@destroy');

And this is my form :

<form action="{{ url('/deleteComment/'.$comment->ID) }}" method="post">
    {{ csrf_field() }}
    <input type="hidden" name="_method" value="DELETE">
    <button type="submit" class="btn btn-sm btn-danger">حذف کردن</button>
</form>

But When I click the button, It doesn't delete anything ... I appreciate any response ...



via Chebli Mohamed

Laravel migration - can't add unsigned and index

When creating migrations, can I add "unsigned" and "index" in this way?

        $table->integer('user_id')->unsiqned()->index();

or only "unsigned", like this:

$table->integer('recipe_id')->unsiqned();

When I do this on my table "user_recipes", only the primary key becomes unsigned. User_id doesn't get "unsigned" nor "index":

public function up()
{
    Schema::create('user_recipes', function (Blueprint $table) {
        $table->increments('recipe_id')->unsiqned();
        $table->integer('user_id')->unsiqned()->index();
        $table->text('recipe_content');
        $table->timestamps();
        $table->boolean('hasbeenconverted', 50);

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

But the above column "recipe_content" becomes "unique" and indexed - how come??

I do the same thing in the table "user_custom_categories", and in this case the user_id became unsigned but no index was added. The auto increment primary key went unsigned also.

public function up()
{
    Schema::create('user_custom_categories', function (Blueprint $table) {
        $table->increments('cat_id')->unsiqned();
        $table->integer('user_id')->unsigned()->index();
        $table->string('custom_category', 50);

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

And on a third table "recipe_category_relations", only the primary "id"-column became unsigned with this code:

public function up()
{
    Schema::create('recipe_category_relations', function (Blueprint $table) {
            $table->increments('id')->unsiqned();
            $table->integer('recipe_id')->unsiqned();
            $table->integer('category_id')->unsiqned();
            $table->timestamps();

           // $table->foreign('recipe_id')->references('recipe_id')->on('user_recipes');
           // $table->foreign('category_id')->references('cat_id')->on('user_custom_categories');

    });
}



via Chebli Mohamed

Test Not Passing From Redirection

I'm wanting to test to see if a user is NOT authenticated and the user tries to access the dashboard then they are are taken to the login page to submit the form.

<?php

use Illuminate\Foundation\Testing\DatabaseTransactions;

class AuthTest extends TestCase {

    use DatabaseTransactions;

    protected $user;
    protected $password = 'testpass123';


    /** @before */
    public function setupUserObjectBeforeAnyTest() {
        $this->app->make('db')->beginTransaction();
        $this->beforeApplicationDestroyed(function () {
            $this->app->make('db')->rollBack();
        });
        $this->user = factory(App\User::class)->create([
            'email' => 'john@example.com',
            'password' => bcrypt($this->password),
        ]);
    }

    /** @test */
    public function a_user_is_redirected_to_dashboard_if_authenticated_and_tries_to_access_login_page()
    {
        $this->actingAs($this->user)
            ->visit(route('login'))
            ->seePageIs(route('dashboard'));
    }

    /** @test */
    public function a_user_is_redirected_to_login_page_if_not_authenticated_and_tries_to_access_dashboard()
    {
        $this->visit(route('dashboard'))
            ->seePageIs(route('login'));
    }
}

In the results from the test below it fails. The word app is a route group prefix.

    1) AuthTest::a_user_is_redirected_to_login_page_if_not_authenticated_and_tries_to_access_dashboard
Did not land on expected page [http://localhost/app/login].

Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'http://localhost/app/login'
+'http://localhost/app/dashboard'



via Chebli Mohamed

@cannot statement from Blade engine not working

I'm trying to use @cannot in my template but I have the following issue. With the code:

@section('content')
    @can('upload-images',$flyer)
        <form action="{{ URL::to('/') }}/{{ $flyer->zip }}/{{ $flyer->street }}/photos" method="POST" class="dropzone" enctype="multipart/form-data">
            {{ csrf_field() }}
        </form>
    @endcan
    @cannot
        <p>Not allowed</p>
    @endcannot
@stop

@cannot throws the following error:

Undefined class constant 'denies'

I know @cannot exists and also that uses Gate::denies, which is the error I'm taking, here is the Github commit where the magic should occur:

http://ift.tt/1P5xB2t

Any clues? Thanks!



via Chebli Mohamed

Laravel 5.2, empty session after redirect, WHY???

I don't understand why I have empty session after redirect? I created session and do redirect but session is empty in template, WHY? Please help me.



via Chebli Mohamed

Laravel 5.0 Upload File using Storage API always returns Forbidden

I'm new to Laravel and I'm trying to upload images to my website using Storage API but laravel always returns "Forbidden" after I submitted my form.

Here's my form (add_company.blade.php) :

{!! Form::model($company = new App\Models\Setting\Organization\Company, ['method' => 'POST', 'action' => 'Setting\Organization\CompaniesController@store', 'files'=>true]) !!}

    <div class="form-group">
        {!! Form::label('CompanyCode', 'Company Code : ', ['class' => 'col-lg-3 col-md-3 col-sm-3 col-xs-3']) !!}

        <div class="col-lg-9 col-md-9 col-sm-9 col-xs-9">
            {!! Form::text('CompanyCode', $company->autoGenerateCode(), ['class' => 'form-control', 'readonly' => true]) !!}
        </div>

    </div>

    <div class="form-group">
        {!! Form::label('Name', 'Company Name : ', ['class' => 'col-lg-3 col-md-3 col-sm-3 col-xs-3']) !!}

        <div class="col-lg-9 col-md-9 col-sm-9 col-xs-9">
            {!! Form::text('Name', null, ['class' => 'form-control']) !!}
        </div>

    </div>

    <div class="form-group">
        {!! Form::label('Logo', 'Company Logo : ', ['class' => 'col-lg-3 col-md-3 col-sm-3 col-xs-3']) !!}

        <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
            <span class="btn btn-default btn-file form-control">
                Browse {!! Form::file('Logo', ['class' => 'form-control', 'id' => 'logo']) !!}
            </span>
        </div>

    </div>

    <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
        {!! Form::submit('Add Company', ['class' => 'btn btn-primary']) !!}
    </div>
{!! Form::close() !!}

Here's the store method in my controller (App\Http\Controllers\Setting\Organization\CompaniesController) :

public function store(CompanyRequest $request){
    if (Request::file('Logo')->isValid())
    {
        $file = Request::file('Logo');
        $extension = $file->getClientOriginalExtension();
        $newFilename = $request->CompanyCode . "_logo";
        Storage::disk('local')->put($newFilename . '.' . $extension,  File::get($file));

        $request->Logo = $newFilename;
    }

    Company::create($request->all());
    flash()->success('Company ' . $request->Name . ' Added.');
    return redirect('company');
}

Laravel doesn't give any error but always returns "Forbidden" every time I submit my form. I didn't change anything in the config/filesystems.php or in the public/.htaccess.

Please help, I've already read many posts about file upload in Laravel 5 but didn't find any answer. Thanks a lot!



via Chebli Mohamed

Automatic translation does not work in Laravel 5.2

After changing the locale name and then print {{ Config::get('languages')[App::getLocale()] }}, it's giving me the locale name i.e. Italiano or Français. But it does not translate the website text into changed locale!

I am using following article for the localization Laravel 5.2 localization also tried Laravel Localizationbut same also there.

From my understanding, it should translate the language automatically!

Need some expert help from the community.



via Chebli Mohamed

Laravel 5 + PostgreSQL: "Database [postgres] not configured." Error

I'm trying to get started with Laravel + PostgreSQL and been following the database tutorial.

Unfortunately, after updating the database configuration file and running php artisan migrate, the following error appears:

  [InvalidArgumentException]
  Database [postgres] not configured.

What puzzles me is that I didn't specify the "postgres" database in the configuration, but another database I set through cPanel, say "example_database".


Here's some relevant parts of my /config/database.php configuration:

'default' => env('DB_CONNECTION', 'postgres')

And inside the connections array of the same file:

'pgsql' => [
        'driver'   => 'pgsql',
        'host'     => env('DB_HOST', 'localhost'),
        'database' => env('DB_DATABASE', 'example_database'), // This seems to be ignored
        'username' => env('DB_USERNAME', 'example_username'),
        'password' => env('DB_PASSWORD', 'example_password'),
        'charset'  => 'utf8',
        'prefix'   => '',
        'schema'   => 'public'
    ],

The actual database credentials I'm using are working perfectly on my SQL Workbench client, so this seems to be a Laravel config problem. Any ideas? I have searched around for at least an hour to no avail.



via Chebli Mohamed

Larave Join table and query

I have 3 table. Users, Accounts and Booking. I have try three table join and year and month wise query. 3 Table diagram

But query booking calculation is show wrong. Its show double quantity.

$january = DB::table('users')
        ->join('bookings', 'users.id', '=', 'bookings.user_id')
        ->join('accounts', 'users.id', '=', 'accounts.user_id')
        ->orderBy('users.room_id','asc')
        ->groupBy('users.id')
        ->whereYear('bookings.bookingdate','=', '2016')
        ->whereMonth('bookings.bookingdate','=','01')
        ->whereYear('accounts.accountdate','=', '2016')
        ->whereMonth('accounts.accountdate','=','01')
        ->select('users.*',
            DB::raw("COUNT(case when bookings.breakfast='on' then 1 else null end) AS t_breakfast"),
            DB::raw("COUNT(case when bookings.lunch='on' then 1 else null end) AS t_lunch"),
            DB::raw("COUNT(case when bookings.dinner='on' then 1 else null end) AS t_dinner"),
            DB::raw("SUM(accounts.amount) AS t_amount")
        )
        ->get();

    dd($january);



via Chebli Mohamed

samedi 30 janvier 2016

I want to write my own laravel authentication system? Suggest plz?

I'm working on a project similar to elnace or freelance, where there are 3 kinds of users, One who works and one who hire, and one more is Admin, so how should i go with this. I think (as much i know) laravel don't support this kind of Authentication and Authorization. thanks



via Chebli Mohamed

How to clear redis cache while keeping session data : Laravel 5

I am using redis as a session driver and I want to clear the cache while keeping the session data, so basically user can stay logged in. Any suggestions regarding restructuring or handling the current situation?

Note: I don't want to use separate redis instance for sessions and other cache data.



via Chebli Mohamed

getting a generic BulkWrite error in MongoDB / Laravel

So I have the following artisan command controller:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use MongoDB;

class TestCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'testcommand';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
        $bulk = new MongoDB\Driver\BulkWrite();
        $bulk->insert(['test', 'data']);
        $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 100);
        $manager->executeBulkWrite('test.test', $bulk, $writeConcern);
    }
}

When I try to run it with php artisan testcommand (it's defined in Kernel.php) I get the following error:

  [MongoDB\Driver\Exception\BulkWriteException]
  BulkWrite error

That is very unhelpfully generic. Any idea what the problem is?



via Chebli Mohamed

How fix image asset when remove public folder?

Hi all I am a new of laravel, After I am remove public folder (http://localhost/movie/public => http://localhost/movie) I can not put image on my laravel project with asset how can I fix.

First I am create folder in public folder uploads and then my code below:

<img src="{{asset('uploads/picc.png')}}">

And when run http://localhost/movie the image dont show,Help me please !!



via Chebli Mohamed

view composer laravel 5.0

I am error facing to sharing data with views,

ErrorException in d280994c1185d651d47347db1597d7ed line 67:
Undefined variable: QandA (View: E:\Web\xampp\htdocs\wifaq-atropos\resources\views\_partials\_footer.blade.php) (View: E:\Web\xampp\htdocs\wifaq-atropos\resources\views\_partials\_footer.blade.php)

And here is my code class AppServiceProvider

public
function boot() {
  View::composer('_partials._footer', function($view) {
    $QandA = \DB::table('qa') - > take(3) - > orderBy('id', 'desc') - > get();
    $view - > with('QandA', $QandA);
  });
}

Here _footer.blade.php file

@foreach($QandA as $QandA)
<div class="post-item">
  <small>JANUARY 2, 2014 BY ADMIN</small>
  <h3><a href="blog-single-sidebar-left.html">{{ $QandA->q }}</a></h3>
</div>
@endforeach

how to fix it ? And other problem when I dicuss conversation on laracast. Its not work button always remain disable. Why? See in link



via Chebli Mohamed

Is it possible to prioritize a package's routes?

This is the scenario: I have the application routes, and I'm extracting the backend as a package, so it now has it's own routes.

But the application currently handles -say, to simplify- 3 types of routes:

  • Application routes, run first
  • Backend routes, run after
  • Application catch everything, run last

So currently, since I got the Backend split, It's routes are registered last like follows:

  • Application routes, run first
  • Application catch everything, run last
  • Backend routes, run after

If you ask for actual code this is my route files pointing to the ROOT CONTEXT I want to extract. Note that once in the package's routes it is registered last and thus the priority lost.

Thanks!



via Chebli Mohamed

Laravel 5 - Cannot find MySQL Stored Procedure

ISSUE: Converting my L4 code to L5.2 and am receiving the following error: SQLSTATE[42000]: Syntax error or access violation: 1305 FUNCTION cr_debug.ENTER_MODULE2 does not exist (SQL: call POPULATE_DAYS_TABLE(20, "01/29/2016")) & SQLSTATE[42000]: Syntax error or access violation: 1305 FUNCTION cr_debug.ENTER_MODULE2 does not exist

ATTEMPTED: I have searched Stackoverflow and Google to find what is happening. I have attempted to change call to EXEC and that created another error stating that my version of MySQL doesn't support call. I just installed the latest version MySQL two weeks ago. I have tried to namespace the procedure call to no avail. I have removed all spaces from function calls within the Stored Procedure (Example: IF (var) is now IF(var) or function (var) is now function(var).

REQUEST: Please assist in helping figure out what is wrong and explain in detail what I am doing wrong with examples, if possible.

NOTES: I have severely shortened the ContractController.php file for brevity. If you need to see the stored procedures I can display those too. The stored procedures are in MySQL. This works in Laravel 4.

DEBUG INFORMATION: ERROR 1 OF 2 PDOException in Connection.php line 390: SQLSTATE[42000]: Syntax error or access violation: 1305 FUNCTION cr_debug.ENTER_MODULE2 does not exist

in Connection.php line 390
at PDOStatement->execute(array()) in Connection.php line 390
at Connection->Illuminate\Database\{closure}(object(MySqlConnection), 'call POPULATE_DAYS_TABLE(20, "01/29/2016")', array()) in Connection.php line 644
at Connection->runQueryCallback('call POPULATE_DAYS_TABLE(20, "01/29/2016")', array(), object(Closure)) in Connection.php line 611
at Connection->run('call POPULATE_DAYS_TABLE(20, "01/29/2016")', array(), object(Closure)) in Connection.php line 391
at Connection->statement('call POPULATE_DAYS_TABLE(20, "01/29/2016")')
at call_user_func_array(array(object(MySqlConnection), 'statement'), array('call POPULATE_DAYS_TABLE(20, "01/29/2016")')) in DatabaseManager.php line 317
at DatabaseManager->__call('statement', array('call POPULATE_DAYS_TABLE(20, "01/29/2016")')) in Facade.php line 218
at Facade::__callStatic('statement', array('call POPULATE_DAYS_TABLE(20, "01/29/2016")')) in computer.php line 15
at computer::storedProcedureCall('20', '01/29/2016') in ContractController.php line 56
at ContractController->store()
at call_user_func_array(array(object(ContractController), 'store'), array()) in Controller.php line 76
at Controller->callAction('store', array()) in ControllerDispatcher.php line 146
at ControllerDispatcher->call(object(ContractController), object(Route), 'store') in ControllerDispatcher.php line 94
at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 96
at ControllerDispatcher->callWithinStack(object(ContractController), object(Route), object(Request), 'store') in ControllerDispatcher.php line 54
at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\ContractController', 'store') in Route.php line 174
at Route->runController(object(Request)) in Route.php line 140
at Route->run(object(Request)) in Router.php line 703
at Router->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in Router.php line 705
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 678
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 52
at Pipeline->Illuminate\Routing\{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 32
at Pipeline->Illuminate\Routing\{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

ERROR 2 OF 2 QueryException in Connection.php line 651: SQLSTATE[42000]: Syntax error or access violation: 1305 FUNCTION cr_debug.ENTER_MODULE2 does not exist (SQL: call POPULATE_DAYS_TABLE(20, "01/29/2016"))

in Connection.php line 651
at Connection->runQueryCallback('call POPULATE_DAYS_TABLE(20, "01/29/2016")', array(), object(Closure)) in Connection.php line 611
at Connection->run('call POPULATE_DAYS_TABLE(20, "01/29/2016")', array(), object(Closure)) in Connection.php line 391
at Connection->statement('call POPULATE_DAYS_TABLE(20, "01/29/2016")')
at call_user_func_array(array(object(MySqlConnection), 'statement'), array('call POPULATE_DAYS_TABLE(20, "01/29/2016")')) in DatabaseManager.php line 317
at DatabaseManager->__call('statement', array('call POPULATE_DAYS_TABLE(20, "01/29/2016")')) in Facade.php line 218
at Facade::__callStatic('statement', array('call POPULATE_DAYS_TABLE(20, "01/29/2016")')) in computer.php line 15
at computer::storedProcedureCall('20', '01/29/2016') in ContractController.php line 56
at ContractController->store()
at call_user_func_array(array(object(ContractController), 'store'), array()) in Controller.php line 76
at Controller->callAction('store', array()) in ControllerDispatcher.php line 146
at ControllerDispatcher->call(object(ContractController), object(Route), 'store') in ControllerDispatcher.php line 94
at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 96
at ControllerDispatcher->callWithinStack(object(ContractController), object(Route), object(Request), 'store') in ControllerDispatcher.php line 54
at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\ContractController', 'store') in Route.php line 174
at Route->runController(object(Request)) in Route.php line 140
at Route->run(object(Request)) in Router.php line 703
at Router->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in Router.php line 705
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 678
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 52
at Pipeline->Illuminate\Routing\{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 32
at Pipeline->Illuminate\Routing\{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

ContractController.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Library\customer;
use App\Library\computer;

class ContractController extends Controller
{
    Protected $layout = 'master';
    public function store()
    {
        // Receive input from Form
        $input = \Input::only([
            'contractterm_id', 'businesstype_id', 'company', 'bcity', 'bphone', 'bstate', 'bstraddr',
            'bzip', 'firstname', 'lastname', 'mobile', 'hcity',
            'hphone', 'hstate', 'hstraddr', 'hzip'
        ]);

        $morepcs_array = \Input::only('addtpcmake','addtpcmodel','addtpcserial','addtpcname');
    /*  
        // Debugging Code
        foreach ($morepcs_array as $textbox_name => $textbox)
            {
                echo "<br><br>".$textbox_name;
                echo "<br>textbox quantity: ".sizeof($textbox);
                foreach($textbox as $value) {
                    if ($value == NULL) {
                        echo "<br>NULL";
                    }
                    else {
                        echo "<br>".$value;
                    }
                }
            }
    */  
        $customer = new customer($input); // Create new customer object. Store $input into this object.
        $computer = new computer; // Create new computer object
        $computer->addtpcs = \Input::get('addtpcs'); // Get the form data for addtpcs and prepare to store it in a database table named addtpcs.
        $computer->save(); // Save the information into the database table addtpcs from the computer object.
        $customer->computer()->associate($computer); // Using the associate function, store the id from the computer table in the database to the customer_id table in the database.
        $customer->save(); // send all of the data to the customer table in the database.

        // $startdate = new day;
        $startdate = \Input::get('contract_date');
        // $customer->startdate()->save($startdate);

        //Log::info('$startdate from controller before it is passed to the StoredProcedureCall method: ' . $startdate);
        //Log::info('$customer->id from controller before it is passed to the StoredProcedureCall method: ' . $customer->id);
        //Computer::storedProcedureCall($customer->id,$startdate);
        //$days = Day::all()->last(); // Never do this.  For testing purposes only.
        // Figure out total contract cost based upon Contract Term and Business Type
        computer::storedProcedureCall($customer->id,$startdate); // Call the MySQL stored procedure.
}

computer.php:

Class computer extends \Eloquent {
 protected $guarded = array();

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

 public static function storedProcedureCall($customer, $contract_date) {
         //Log::info('$contract_date after it is received from the controller: ' . $contract_date);
         //Log::info('$data after it is received from the controller: ' . $data);
         return \DB::statement('call POPULATE_DAYS_TABLE(' . $customer . ', "'.$contract_date.'")');
    }
 public static $rules = array();
  }



via Chebli Mohamed

Can I restrict an Eloquent model from returning guarded properties in Laravel?

Is there an easy way to not return guarded properties for an eloquent model?

I want to return a User and build a similar User object on the front end. However, I don't want to return the Users password, type_id, remember_token and other properties. Is there a simple way I can restrict the application from returning these properties? I'm aware I can a write a method or attribute that returns only the values I want, but I'm wondering if there's an unguarded() function for eloquent or collections.

If not, how would you recommend doing this. I'd probably scope it as opposed to wrting an attribute, mutator or method.



via Chebli Mohamed

Laravel 5.1 Sort the result of a search filter

I have searched the site and I can choose various filters. This already works. He returns and makes pagination correctly.

Example:

/empresas?estado=2&tipo=3&page=2

The problem is when I click to order (one form select).

It does not maintain the current URL, it simply does:

/empresas?ordenar=nome

It should be something like:

/empresas?estado=2&tipo=3&ordenar=nome&page=3

I made an append such as paging does.

But it did not work.

The Controller:

$estados = DB::table('estados')->orderBy('nome', 'asc')->get();
$tipos = DB::table('tipos')->orderBy('nome', 'asc')->get();

$word = Input::get('query');
$ordenar = Input::get('ordenar');
$estado = Input::get('estado');
$tipo = Input::get('tipo');

$query = Empresas::with('usuario')
    ->with('estado');

if($word)
    $query->where('descricao', 'LIKE', '%' . $word . '%')
        ->orWhere('carta', 'LIKE', '%' . $word . '%');

if($estado)
    $query->whereIn('estado_id', $estado);

if($tipo)
    $query->where('tipo_id', $tipo);

if($ordenar)
    $query->orderby($ordenar, 'asc');

$empresas = $query->orderBy('updated_at', 'desc')->paginate(18);

return view("pages.empresas.index")
    ->with('estados', $estados)
    ->with('tipos', $tipos)
    ->with(compact('empresas', 'word', 'ordenar', 'estado','tipo'));

In VIEW:

I make a foreach bringing the fields normally and the phaco append to render that already works

<center>{!! str_replace('/?','?', $empresas->appends(Input::query())->render()) !!}</center>

I have a form to sorting by perhaps the error is it

 <form action="/empresas" method=get>
     <select class="form-control m-b" name="ordenar" onchange="this.form.submit()">
     <option value="" disabled="" selected="">Ordenar por...</option>
     <option value="nome">Nome</option>                                                       
     </select>
</form>



via Chebli Mohamed

Variable In Controller Then Function

For some reason my variable doesn't pass to my SMS function?

public function visitor_signin(Request $request)
{

$data = $request->first_name;
$mobile = $request->mobile;

SMS::send('text::invite', ['data' => $data], function($sms) {
 $sms->to($mobile);
});

}

I get the error: Undefined variable: mobile



via Chebli Mohamed

Use xmp tag in Laravel blade

I would like to add xmp tag in my laravel 5 blade.

@extends('app')

@section('content')
<xmp theme="united" style="display:none;">
    # Markdown text goes in here

</xmp>

<script src="http://ift.tt/1RSMOK8"></script>

@endsection

I'm trying to embed some markdown here. But it only works without the blade part.

Any suggestions?



via Chebli Mohamed

Laravel 5 routing underscore/dash

Hi have an issue with a particular URL structure I am after.

Let's say we are comparing two products and I have it set up like so:

Route::get('/{company_slug}/{name_slug}/vs/{company_slug_two}/{name_slug_two}', 'CompareController@compareTwoProducts');

http://ift.tt/1PpkEUZ

but ideally I'd like to create url's like this:

http://ift.tt/1QzoyJK

I don't believe dashes work within the route and it could create issues with the slug I suppose, it seems like underscores are supported within the laravel route system so I thought I could set up a URL structure like so:

Route::get('/{company_slug}_{name_slug}_vs_{company_slug_two}_{name_slug_two}', 'CompareController@compareTwoProducts');

However this does not work, not sure why (notfoundhttpexception) and my thinking was to replace the underscores by dashes with the htaccess.

Could this work or any alternative suggestions?



via Chebli Mohamed

Installing Omnipay with laravel 5.2

I am developing an eCommerce website using Laravel 5.2 and trying to install Omipay ( payment processing library ) via composer. But composer throwing the following errors when I tried.

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

Problem 1
- Conclusion: don't install omnipay/omnipay 2.3.2
- Conclusion: don't install omnipay/omnipay v2.3.1
- Conclusion: remove symfony/http-foundation v3.0.1
- Installation request for omnipay/omnipay ^2.3 -> satisfiable by omnipay/omnipay[2.3.2, v2.3.0, v2.3.1].
- Conclusion: don't install symfony/http-foundation v3.0.1
- omnipay/omnipay v2.3.0 requires omnipay/common ~2.3.0 -> satisfiable by omnipay/common[2.3.2, v2.3.0, v2.3.1, v2.3.3, v2.3.4].
- omnipay/common 2.3.2 requires symfony/http-foundation ~2.1 -> satisfiable by symfony/http-foundation[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.37, 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.13, 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.7.9, v2.8.0, v2.8.1, v2.8.2].

Please suggest me the solution how could I fix that?

Thanks



via Chebli Mohamed

Laravel : having the same element on each of my pages

On Laravel 5.2, I'm trying to put two menus (X latest contents, and the same for a specific user) on near every page.

The lazy way would be to generate those arrays in each of the controllers, but is there a way to generate it when the templating system needs them ?

For instance, my template could call something like {{ $menu }} and the menu would be generated only when this was present ?



via Chebli Mohamed

Laravel 5.2 -> fill up tables on registration

i have 2 accounts, business\company user and private user, they share some attributes as email,password,name. but there is a need to store more things about the businesses. so i have two tables.

main table: users company: company is connected through Foreign Key(user_ID). So far i was not able to write anything into company table :/ any advice ?

business model:

class Company extends Model
{
        protected $fillable = ['ICO'];
        public function user() {
        return $this->belongsTo('App\User');
}}

user model:

class User extends Authenticatable {
    protected $fillable = [
        'firstname','middlename','lastname', 'email', 'password','usertype',];
    protected $hidden = ['password', 'remember_token',];
    public function company(){
    return $this->hasMany('App\Company');
    }
}

migration-company

public function up() {
        Schema::create('companyuser', function (Blueprint $table) {   
        $table->integer('user_id')->unsigned()->nullable();
        $table->integer('ICO');
        $table->timestamps();
        $table->foreign('user_id')->references('id')->on('users')
              ->onDelete('cascade');    
        });
    }

AuthController.php

   $user = User::create([
                        'firstname' => $data['firstname'],
                        'lastname' => $data['lastname'],
                        'middlename' => $data['middlename'],
                        'usertype' => $data['usertype'],
                        'email' => $data['email'],
                        'password' => bcrypt($data['password']),
            ]);
    //no problem with this upper part but with this part on bottom.
     $company = Company::create([
               'ICO' => $data[ICO],
           ]);



via Chebli Mohamed

Distinguish between JSON object and JSON array in Laravel

I need to validate a JSON payload to contain a JSON object for particular field. As far as I can see, both JSON objects and JSON arrays are converted to PHP arrays in Laravel's Illuminate\Http\Request

See the example below.

Controller.php

private static function getType($o) {
    if (is_object($o)) {
        return "Object";
    } else if (is_array($o)) {
        return "Array";
    }
    return "Unknown";
}

public function test(Request $request) {
    $input = $request->all();
    $response = [];
    foreach ($input as $key => $value) {
        $response[$key] = Controller::getType($value);
    }
    return response()->json($response);
}

test is the function that get hits on an HTTP request.

Here is a sample request and response from Controller.php

Request

{
    "obj1": {},
    "obj2": {
        "hello": "world"
    }
    "arr1": [],
    ,
    "arr2": ["hello world"]
}

Response

{
  "obj1": "Array",
  "obj2": "Array",
  "arr1": "Array",      
  "arr2": "Array"
}

Is there a way I can validate fields obj1 and obj2 to only contain JSON objects here?



via Chebli Mohamed

Laravel error. Failed to open dir: not implemented

I'm trying this script to render a gallery from all the pictures in a folder in a Laravel project. I got this error

ErrorException in ArmadiController.php line 32: opendir(http://ift.tt/1PGYtFj): failed to open dir: not implemented

this is the function in the controller that generates the error. How can i make it work or do something similar?

public function gallery()
    {
        $data = [];
        $folder_path = asset('images');
        $num_files = glob($folder_path . "*.{JPG,jpg,gif,png,bmp}", GLOB_BRACE);
        $folder = opendir($folder_path);
        if ($num_files > 0) {
            while (false !== ($file = readdir($folder))) {
                $file_path = $folder_path . $file;
                $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                if ($extension == 'jpg' || $extension == 'png' || $extension == 'gif' || $extension == 'bmp') {
                    $data[] = $file_path;
                }
            }
        } else {
            return "the folder was empty !";
        }
        closedir($folder);
        return $data;
    }



via Chebli Mohamed

How to render Wiris mathematical expressions in Angularjs

I have successfully integrated Wiris plugin into Ckeditor. Every thing works just fine except the front view. I am programming with laravel5 and using Angularjs to handle my views.

When I create a mathematical expression for example (x - 1) Angularjs will present it as x-1 .

I even used ng-bind-html to no avail. But at the level of the editor everything is fine such that I can create and save it without any problems. I am using Wiris for Ckeditor and PHP.

When I use the {!! !!} for the blade template engine and it is just fine. How do I archive this in AngularJs?



via Chebli Mohamed

More than only one methods to authentication middleware on laravel

I am having this on my laravel project and i want to add more methods to the exept array. And i could not figure it out how i should write it?

public function __construct()
    {
    $this->middleware('auth', [ 'except' => 'index' ]);

    }



via Chebli Mohamed

Laravel handle default route if optional parameter is not in the list

I define optional parameter "type" in the route and limit acceptable values (A,B or C) with where clause:

Route::get('test/{type?}', ['uses' => 'MyController@index'])->where('type', 'A|B|C');

If type value is different to A,B or C (e.g. "X") framework returns error page:

NotFoundHttpException in RouteCollection.php

In such case I would like to ignore received optional parameter and handle route as it is with no specified parameter i.e.: test/

How can it be implemented?



via Chebli Mohamed

Laravel- Redirect user to profile page

I am trying to redirect the user if he logs in for the first time to step2 page, I have tried the following

    public function postLogin(Request $request){

    $credentials = $request->only('login_email', 'login_password');
    $credential = ['email'=> $credentials['login_email'], 'password' => $credentials['login_password']];
    if (Auth::attempt($credential)) {
        // if profile not set, redirect to step 2 page
        if(Auth::user()->first_login) {

            $this->getStep2(Auth::user()->id);


        }
}

but it shows me

{"login":true}

My getStep2() is like

    public function getStep2($id){
    $genres = Track::orderBy('genre', 'asc')->groupBy('genre')->get();
    $countries = Country::all();
    $categories = Category::where('parent_id',  '')->get();
    $user_id = $id;
    return view('users.step2', compact('genres', 'countries', 'categories', 'user_id'));
}



via Chebli Mohamed

Error : Configuring Email in Laravel 5 Project

I am using email service to confirm user's registration to my new website. I heard some folks said about configuring the email setting in .env and config/mail.php . I've configured it using gmail setting with this:

my .env file:

APP_ENV=local
APP_DEBUG=true
APP_KEY=eN3KtYOe7uNiYwFLgoZDQEPf4YC85HFc

DB_HOST=localhost
DB_DATABASE=mydatabase
DB_USERNAME=root
DB_PASSWORD=

CACHE_DRIVER=file
SESSION_DRIVER=file

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=mygmailaccount@gmail.com
MAIL_PASSWORD=__myGmailPassword__
MAIL_ENCRYPTION=tls

My config/mail.php file:

<?php

return [

    'driver' => 'smtp',
    'host' => 'smtp.gmail.com',
    'port' => 587,
    'from' => ['address' => 'mygmailaccount@gmail.com', 'name' => 'somename'],
    'encryption' => '',
    'username' => 'mygmailaccount@gmail.com',
    'password' => '__mygmailpassword__',
    'sendmail' => '/usr/sbin/sendmail -bs',
    'pretend' => false,
];

After i tried to login, i got this error :

Swift_TransportException in AbstractSmtpTransport.php line 383:

Expected response code 250 but got code "530", with message "530 5.7.0 Must issue a STARTTLS command first. h66sm30269295pfj.52 - gsmtp

What could possibly wrong? How to make it works? Thanks.



via Chebli Mohamed

Eloquent & Carbon Time Difference

I have a basic table which captures time and attendance.

I'm trying to out put the total hours on site, from my eloquent query:

$attendance = DB::table('staff_attendances')
        ->whereBetween('in_date', array($date1, $date2))->where('staff_id', $ID)->select('first_name', 'last_name', 'in_date', 'out_date', 'in_time', 'out_time')->get();

I get the following back in json.

[{"first_name":"TestFirst","last_name":"TestLast","in_date":"2016-01-30","out_date":"2016-01-30","in_time":"11:40:34","out_time":"12:41:10"},

{"first_name":"TestFirst","last_name":"TestLast","in_date":"2016-01-30","out_date":"2016-01-30","in_time":"13:02:27","out_time":"14:02:32"}]

Which method would be best to out put total hours on site?

I've tried using carbon with the following:

$startTime = Carbon::parse($attendance->in_time);
$finishTime = Carbon::parse($attendance->out_time);
$totalDuration = $finishTime->diffInHours($startTime);

But I get "Trying to get property of non-object"



via Chebli Mohamed

in laravel 5, which function parameter does the /?page= url argument feed?

i need to have two different paginators in one page, using ajax to dynamically load the paged content in each of the div's.

the thing that concerns me is where to feed the page argument in my controller, that corresponds to the page number i want to retrieve from the paginator. i don't seem to have sorted that one out, although i have been running through the Builder, Paginator, AbstractPaginator source code thoroughly... guess my code architecture comprehension needs a boost....

the technique that i follow is render() the pager controls, then modify them with jquery in a way that href=/random/route/?page=4 becomes onclick=/random/route/pager-type/4

i have setup the appropriate routes ** /random/route/{pager-type?}/{page-no?} ** but i have no understanding on how to use the page-no argument in extracting the page i am interested in from the pager instance.

thanks everyone in advance!



via Chebli Mohamed

One to Many relationship in Laravel Eloquent giving undefine method

I am having the said problem when defining one to many relationship with two models, the Student and Enrollment. When accessing the table from another table using :

$enrollment->students()->first_name

Can someone help me on this.

Enrollment

    protected $fillable = [
    'subject_code',
    'subject_description',
    'section',
    'schedule',
    'room_no',
    'no_of_units'
];

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

Student

   protected $fillable = [
    'student_id',
    'first_name',
    'last_name',
    'middle_name',
    'birthdate',
    'fathers_name',
    'mothers_name',
    'phone_no',
    'degree_id',
    'city_id',
    'address'
];

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

Here's the table for the students and enrollment accordingly

        Schema::create('enrollments', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('student_id');
        $table->string('subject_description');
        $table->string('subject_code');
        $table->time('schedule');
        $table->string('room_no');
        $table->integer('no_of_units');
        $table->string('section');
        $table->timestamps();
    });

           $table->increments('id');
        $table->integer('student_id');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('middle_name');
        $table->date('birthdate');
        $table->string('fathers_name');
        $table->string('mothers_name');
        $table->string('phone_no');
        $table->string('address');
        $table->integer('city_id');
        $table->integer('degree_id');
        $table->timestamps();
    });



via Chebli Mohamed

JWT Auth and Satellizer - Increase expiry token time for mobile app

I am using Ionic and satellizer along with Laravel and JWT auth to create an API.

Everything is good, but the one issue is the token being removed from local storage after an hour or so.

I really want the token to exist until the user logs out, as they will be using a phone app and not wishing to log in everytime.

This is first experience with tokens, so I am not sure on how this normally works. I imagine people done normally store tokens for ever?

This is in my Ionic controller:

    $auth.login(credentials).then(function() {
        $http.get($rootScope.apiURL + 'authenticate/user').success(function(response){
            var user = JSON.stringify(response.user);
            localStorage.setItem('user', user);
        });
    })

This sets a Satellizer token and also the user information in Local storage.

In Laravel for the API call:

public function authenticate(Request $request)
{
    $credentials = $request->only('email', 'password');

    try {
        // verify the credentials and create a token for the user
        if (! $token = JWTAuth::attempt($credentials)) {
            return response()->json([
                'error'         => 'invalid_credentials',
                'error_message' => 'Invalid username or password'
            ], 401);
        }
    } catch (JWTException $e) {
        // something went wrong
        return response()->json(['error' => 'could_not_create_token'], 500);
    }

    // if no errors are encountered we can return a JWT
    return response()->json(compact('token'));
}



via Chebli Mohamed

How to set up Browserify with Elixir and Browserify Shim on Laravel 5?

I am trying to set up Browserify with Elixir and Browserify Shim on Laravel 5.2 to use Gulp with my JavaScript files, but I didn't have much luck so far. This should be pretty straightforward to do, but it isn't.

Here is my package.json

{
  "private": true,
  "devDependencies": {
    "gulp": "^3.8.8"
  },
  "dependencies": {
    "bootstrap-sass": "^3.0.0",
    "browserify-shim": "^3.8.12",
    "jquery": "^2.2.0",
    "jquery-ui": "^1.10.5",
    "laravel-elixir": "^4.0.0"
  },
  "browser": {
    "app": "./resources/assets/js/app.js",
    "utils": "./resources/assets/js/utils.js",
  },
  "browserify": {
    "transform": [
      "browserify-shim"
    ]
  },
  "browserify-shim": {
    "app": {
      "depends": [
        "jquery:$",
        "utils:Utils"
      ]
    },
    "utils": {
      "depends": [
        "jquery:$"
      ]
    },
  }
}

gulpfile.js

var elixir = require('laravel-elixir');

elixir(function (mix) {
    mix.browserify('main.js', './public/js/bundle.js');
});

Entry script main.js looks like this:

var $ = require('jquery');
var Utils = require('utils');
var App = require('app');

app.js

var App = {
     init: function(){
         console.log(Utils);
         Utils.doSomething();
     }
    //other methods
};

In short: Utils depends on $, and App depends on both $ and Utils.

When I hit gulp from terminal, bundle.js is correctly created. All scripts are wrapped up in Browserify code (as expected). Each script has all included dependencies, like I configured in package.json so this part looks good as well.

The problem is that all my included dependencies are empty objects. For example, Utils in app.js is empty, and I get an error when I try to call its method "doSomething". Console log prints out an empty object "{}" instead of real object. The only correctly included script is jQuery and it's not an empty object.

What could be wrong here? Do I need to make some changes in my JS files or in configuration to make this work? It looks like I'm pretty close to the solution, but it still does not work and I can't use it at all.



via Chebli Mohamed

vendredi 29 janvier 2016

Laravel Permission Denied

Tonight, I tried to run composer install and all the dependencies installed correctly, and then composer ran php artisan clear compiled and I ran into trouble.

Here's the error it returned:

> php artisan clear-compiled


  [ErrorException]                                                                                                        
  file_put_contents(/srv/something/site/bootstrap/cache/services.php): failed to open stream: No such file or directory  


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



  [RuntimeException]  
  Error Output:       



install [--prefer-source] [--prefer-dist] [--dry-run] [--dev] [--no-dev] [--no-plugins] [--no-custom-installers] [--no-autoloader] [--no-scripts] [--no-progress] [-v|vv|vvv|--verbose] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--ignore-platform-reqs] [--] [<packages>]...

Naturally, I googled it and found everyone on the laracast forums saying to make the directory I was missing, so I did and the command ran again fine. When I went to any page I got thew file_put_contents(/differentNameDependingOnPageButAlwaysRandomLettersAndNumbers.php): failed to open stream: Permission denied

For example here's the traceback for the login page:

ErrorException in Filesystem.php line 81:
file_put_contents(/8ff8cea6e3bb10ecec87b9d62c64f9768c4c4ab1.php): failed to open stream: Permission denied
in Filesystem.php line 81
at HandleExceptions->handleError('2', 'file_put_contents(/8ff8cea6e3bb10ecec87b9d62c64f9768c4c4ab1.php): failed to open stream: Permission denied', '/srv/something/site/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php', '81', array('path' => '/8ff8cea6e3bb10ecec87b9d62c64f9768c4c4ab1.php', 'contents' => '<?php $__env->startSection('title'); ?> Admin Login <?php $__env->stopSection(); ?> <?php $__env->startSection('form'); ?> <form class="form-horizontal" method="POST" action = "login"> <?php echo e($error); ?><?php /*TODO this doesn't show up now, when you do login make it show up*/ ?> <fieldset> <!-- Form Name --> <h1 class="section-heading" style="text-align: center;">Login</h1> <!-- Text input--> <div class="form-group"> <label class="col-md-4 control-label" for="email">Email</label> <div class="col-md-4"> <input id="email" name="email" type="email" id = "email" placeholder="user@domain.com" class="form-control input-md" required=""> </div> </div> <!-- Password input--> <div class="form-group"> <label class="col-md-4 control-label" for="password">Password</label> <div class="col-md-4"> <input id="password" name="password" type="password" placeholder="********" class="form-control input-md" required=""> </div> </div> <!-- Button --> <div class="form-group"> <label class="col-md-4 control-label" for="Submit"></label> <div class="col-md-4"> <button id="submit" name="submit" class="btn btn-primary">Submit</button> </div> </fieldset> </form> <?php $__env->stopSection(); ?> <?php $__env->startSection('message'); ?> <p class="text-muted" style="text-align:center">Don't have an account yet? Click <a href="../register">here</a> to register.</p> <?php $__env->stopSection(); ?> <?php echo $__env->make('auth.partials.master', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>', 'lock' => false))
at file_put_contents('/8ff8cea6e3bb10ecec87b9d62c64f9768c4c4ab1.php', '<?php $__env->startSection('title'); ?> Admin Login <?php $__env->stopSection(); ?> <?php $__env->startSection('form'); ?> <form class="form-horizontal" method="POST" action = "login"> <?php echo e($error); ?><?php /*TODO this doesn't show up now, when you do login make it show up*/ ?> <fieldset> <!-- Form Name --> <h1 class="section-heading" style="text-align: center;">Login</h1> <!-- Text input--> <div class="form-group"> <label class="col-md-4 control-label" for="email">Email</label> <div class="col-md-4"> <input id="email" name="email" type="email" id = "email" placeholder="user@domain.com" class="form-control input-md" required=""> </div> </div> <!-- Password input--> <div class="form-group"> <label class="col-md-4 control-label" for="password">Password</label> <div class="col-md-4"> <input id="password" name="password" type="password" placeholder="********" class="form-control input-md" required=""> </div> </div> <!-- Button --> <div class="form-group"> <label class="col-md-4 control-label" for="Submit"></label> <div class="col-md-4"> <button id="submit" name="submit" class="btn btn-primary">Submit</button> </div> </fieldset> </form> <?php $__env->stopSection(); ?> <?php $__env->startSection('message'); ?> <p class="text-muted" style="text-align:center">Don't have an account yet? Click <a href="../register">here</a> to register.</p> <?php $__env->stopSection(); ?> <?php echo $__env->make('auth.partials.master', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>', '0') in Filesystem.php line 81
at Filesystem->put('/8ff8cea6e3bb10ecec87b9d62c64f9768c4c4ab1.php', '<?php $__env->startSection('title'); ?> Admin Login <?php $__env->stopSection(); ?> <?php $__env->startSection('form'); ?> <form class="form-horizontal" method="POST" action = "login"> <?php echo e($error); ?><?php /*TODO this doesn't show up now, when you do login make it show up*/ ?> <fieldset> <!-- Form Name --> <h1 class="section-heading" style="text-align: center;">Login</h1> <!-- Text input--> <div class="form-group"> <label class="col-md-4 control-label" for="email">Email</label> <div class="col-md-4"> <input id="email" name="email" type="email" id = "email" placeholder="user@domain.com" class="form-control input-md" required=""> </div> </div> <!-- Password input--> <div class="form-group"> <label class="col-md-4 control-label" for="password">Password</label> <div class="col-md-4"> <input id="password" name="password" type="password" placeholder="********" class="form-control input-md" required=""> </div> </div> <!-- Button --> <div class="form-group"> <label class="col-md-4 control-label" for="Submit"></label> <div class="col-md-4"> <button id="submit" name="submit" class="btn btn-primary">Submit</button> </div> </fieldset> </form> <?php $__env->stopSection(); ?> <?php $__env->startSection('message'); ?> <p class="text-muted" style="text-align:center">Don't have an account yet? Click <a href="../register">here</a> to register.</p> <?php $__env->stopSection(); ?> <?php echo $__env->make('auth.partials.master', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>') in BladeCompiler.php line 102
at BladeCompiler->compile('/srv/something/site/resources/views/auth/login.blade.php') in CompilerEngine.php line 51
at CompilerEngine->get('/srv/something/site/resources/views/auth/login.blade.php', array('__env' => object(Factory), 'app' => object(Application), 'error' => '')) in View.php line 135
at View->getContents() in View.php line 106
at View->renderContents() in View.php line 80
at View->render() in Response.php line 53
at Response->setContent(object(View)) in Response.php line 197
at Response->__construct(object(View)) in Router.php line 1030
at Router->prepareResponse(object(Request), object(View)) in ControllerDispatcher.php line 95
at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{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 96
at ControllerDispatcher->callWithinStack(object(authController), object(Route), object(Request), 'getAdminLogin') in ControllerDispatcher.php line 54
at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\authController', 'getAdminLogin') in Route.php line 174
at Route->runController(object(Request)) in Route.php line 140
at Route->run(object(Request)) in Router.php line 703
at Router->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{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 705
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 678
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 52
at Pipeline->Illuminate\Routing\{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 32
at Pipeline->Illuminate\Routing\{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 132
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99
at Kernel->handle(object(Request)) in index.php line 54

So far, to try to fix this I've done the following:

  1. Checked permissions, changed everything to 777 and to be owned by www-data
  2. Tried recloning the empty repository with no vendor file, to no avail, same error on composer install
  3. Ran php artisan cache:clear
  4. Ran php artisan clear-compiled
  5. Ran php artisan dump-autoload
  6. Modified site/config/view.php on an irc suggestion, and changed compiled' => realpath(storage_path().'/framework/views') to 'compiled' => storage_path('framework/views'), which yielded a different error: file_put_contents(/srv/something/site/storage/framework/views/8ff8cea6e3bb10ecec87b9d62c64f9768c4c4ab1.php): failed to open stream: No such file or directory (probably because it's not supposed to be there, but who knows this information could be useful.)

All of this to no avail. The weird part is this issue seemingly showed up out of nowhere. Thanks for the help!



via Chebli Mohamed

Laravel Validation Error customise format of the Response

I am working with L5 Form Requests and don't I just love Taylor! Well, I am doing some AJAX requests and I still want to retain my form requests. The problem is that in the case of a validation error the Validator just returns a 422 error response and flashes the errors, but my AJAX frontend expects a very specific format of response from server whether validation is successful or not.

I want to format the response on Validation errors to something like this

return json_encode(['Result'=>'ERROR','Message'=>'//i get the errors..no problem//']);

My problem is how to format the response for the form requests, especially when this is not global but done on specific form requests.

I have googled and yet not seen very helpful info. Tried this method too after digging into the Validator class.

// added this function to my Form Request (after rules())
    public function failedValidation(Validator $validator)
{
    return ['Result'=>'Error'];
}

Still no success.



via Chebli Mohamed

Laravel validation throwing "NotFoundHttpException" when used in PostMan but works in Angular $http request

I am creating an API but stuck debugging.

Using this in my controller method:

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

If I call that route with PostMan I get a not found error return by Laravel's debugging screen.

However the API call works fine when using an Angular (ionic) $http request.

Any help?



via Chebli Mohamed

Laravel 5 missing required parameters on destroy route

I recently upgraded from laravel 5.1 to 5.2 and now I'm getting an error of Missing required parameters for [Route: example.destroy] [URI: example/{args}].

The error occurs here: <form class="form-horizontal" action="<?php echo route('example.destroy'); ?>" method="post"> on the action attribute of the form.

Route

Route::resource('example', 'ExampleController');

When I was in 5.1, there was no error with this line. Just went I upgrade to 5.2, it now occurs.

The functionality of this is that it will allow user to delete multiple entries by checking the checkboxes that they wish to be deleted. Then upon submit, it will redirect to the destroy method on the controller.



via Chebli Mohamed

Laravel 5 database table relationships

I am starting with learning the database table relationships in Laravel 5. As a cakePHPer something just work a little bit different. My first test is this...

Table containing different sql_types:

class ElementFieldType extends Model {

    protected $fillable = ['name', 'sql_type'];

}

Table containing fields linked to the sql_types in the ElementFieldType Model (element_field_type_id is a foreign key):

class ElementField extends Model {

    protected $fillable = ['api', 'element_field_type_id', 'label', 'type'];

    public function type() {
        return $this->hasOne('App\Models\ElementFieldType');
    }

}

In my controller after finding the ElementField, I want to access the sql_type using:

$field = ElementField::find($id);
echo $field->type->sql_type;

But I get below error, meaning to what I can tell, that there should be an element_field_id key in ElementFieldType, but that cannot be right.

What am I doing wrong?

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'element_field_types.element_field_id' 
in 'where clause' (SQL: select `sql_type` from `element_field_types` 
where `element_field_types`.`element_field_id` = 1 and `element_field_types`.`element_field_id` 
is not null limit 1)



via Chebli Mohamed

Difficulty in executing laravel 5.2 database query

This might be silly question, but since I am new to laravel, I am finding it somewhat difficult to setup database. I am using laravel 5.2. IN config>database.php these are my settings

'default' => env('DB_CONNECTION', 'mysql'),

and for mysql :

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

Then I also changed .env and .env.example file's settings

DB_HOST=localhost
DB_DATABASE=larasite
DB_USERNAME=root
DB_PASSWORD=""

Now when in routes.php I have this code:

Route::get('about', function(){
  $posting = DB::query('select * from posts');
  dd($posting);
});

And then when I visit localhost:8000/about I get following error.

Builder {#118 ▼
#connection: MySqlConnection {#114 ▶}
#grammar: MySqlGrammar {#115 ▶}
#processor: MySqlProcessor {#116}
#bindings: array:6 [▶]
+aggregate: null
+columns: null
+distinct: false
+from: null
+joins: null
+wheres: null
+groups: null
+havings: null
+orders: null
+limit: null
+offset: null
+unions: null
+unionLimit: null
+unionOffset: null
+unionOrders: null
+lock: null
#backups: []
#bindingBackups: []
#operators: array:26 [▶]
#useWritePdo: false
}

I noticed that, even If I change settings and enter wrong details, I get same error. What's happening? How to solve this?



via Chebli Mohamed

How to create two separate login/register sections in Laravel 5

How can I create user login/register pages and business login/register pages in Laravel 5. My AuthController uses:

use AuthenticatesAndRegistersUsers, ThrottlesLogins;

My routes.php is using:

Route::auth();

This is fine for user registration. How can I add a seperate registration for another entity that is different from the user?



via Chebli Mohamed

Elequent Relationships Error

I have created a posts table & comments table for posts comments. I want to get my posts with their comments ...

In my Post Model :

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

In my Comment Model :

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

And this is my Controller :

$post = Post::findOrFail($ID)->comments;
return view('show', compact('post'));

But I get this error : Undefined property: Illuminate\Database\Eloquent\Collection::$ID

What is my problem ?



via Chebli Mohamed

Laravel 5.2, Input::all() is empty

I have strange problem. On localhost evrything is ok. But on my production website function Input::all() return empty Array.

For example http:://mypage.com?action=run etc.

nginx configuration

    server {
root /usr/share/nginx/www/g2g/public;
index index.html index.htm index.php;
server_name mypage.com www.mypage.com;

location / { 
    try_files $uri $uri/ /index.html /index.php;
}   

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;

    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
}   

}



via Chebli Mohamed

Laravel Time Difference Sum

I have a basic table which captures all sign in and out of a member of staff.

I am using laravel for my back-end and im struggling how to get the total number of hours on site.

ID | in_time   | out_time | in_date    | out_date
1  | 21:22:49  | 21:46:05 | 2016-01-28 | 2016-01-28
2  | 08:12:12  | 14:12:01 | 2016-01-28 | 2016-01-28

See my query so far

$date1 = '2015-01-28';
$date2 = '2015-01-28';

$attendancehours = DB::table('staff_attendances')->whereBetween('in_date', array($date1, $date2))->where('id', $sID)
        ->get();

How would I output total hours on site for that daterange?



via Chebli Mohamed

laravel update from 5.1 to 5.2 composer update error

I am trying to update laravel from 5.1 to 5.2 . I followed the instruction as according to update doc but I am getting this error when running composer udpate:

Error Output: PHP Fatal error: Call to undefined method Illuminate\Foundation\Application::bindShared() in /my_app/vendor/illuminate/html/HtmlSe rviceProvider.php on line 36

I've looked up this issue and saw that people were getting this issue when updating to version 5.1 and saw that the method bindShared has been replaced with singleton(), but I don't want to mess with vendor files. Here is my config/app.php providers and aliases arrays:

'providers' => [

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

    /*
     * Application Service Providers...
     */
    App\Providers\AppServiceProvider::class,
    App\Providers\EventServiceProvider::class,
    App\Providers\RouteServiceProvider::class,
    App\Providers\ViewComposerServiceProvider::class,
    Laracasts\Flash\FlashServiceProvider::class,
    Baum\Providers\BaumServiceProvider::class

],

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

'aliases' => [

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

],

and here is my composer.json:

{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"repositories": [{
    "type": "vcs",
    "url": "http://ift.tt/1WRC127"
    }],
"require": {
    "php": ">=5.5.9",
    "laravel/framework": "5.2.*",
    "doctrine/dbal": "^2.6@dev",
    "illuminate/html": "^5.0@dev",
    "laracasts/flash": "dev-master",
    "fairholm/elasticquent": "dev-feature/laravel-5",
    "baum/baum": "~1.1"
},
"require-dev": {
    "fzaninotto/faker": "~1.4",
    "mockery/mockery": "0.9.*",
    "phpunit/phpunit": "~4.0",
    "phpspec/phpspec": "~2.1",
    "symfony/dom-crawler": "~3.0",
    "symfony/css-selector": "~3.0"

},
"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},
"autoload-dev": {
    "classmap": [
        "tests/TestCase.php"
    ]
},
"scripts": {
    "post-install-cmd": [
        "php artisan clear-compiled",
        "php artisan optimize"
    ],
    "post-update-cmd": [
        "php artisan clear-compiled",
        "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"
},
"minimum-stability": "dev",
"prefer-stable": true
}

any idea what I should do to fix this? I started with a 5.1 version install of laravel.



via Chebli Mohamed