Laravel 5 – Conditionally append variables

A few words before

I know that you can append variables to model arrays and json representations by using the protected $appends = ["your", "vars", "here"]; array. But imagine the following situation:

The situation

Our use case would be a fictional game or similiar:

Imagine that we have a User model that holds simple information about an (human) user, like the full name, address and so on.

Now, we also have a Faction model that represents the faction/origin/guild/… of this user.

The Faction model is eager-loaded when retrieving users, because the Faction name is wanted almost every time when displaying the user information.

A User also has DailyStatistics, which holds some information about their daily scores (simple points would be enough).

The Clue

Because I want to know the points of the a faction, which is the sum of the user points, I thought about appending a new variable totalPoints.

The getTotalPointsAttribute function would look like this:

function getTotalPointsAttribute(){
    return $this->users->sum->getTotalPoints();
}

The problem

Everytime when we retrieve a user now, the eager-loaded faction would also want to calculate the totalPoints attribute. That means, that we have a lot of overhead per user.

The question

Is there a way to avoid situations like this? Can I “conditionally” append variables? Are properties calculated when they are hidden?

I tried to wrap the totalPoints variable in a simple function, instead of an accessor instead. The problem is, that Frontend-Frameworks like VueJS would need access to the totalPoints variable (or to an endpoint to retrieve that value, but this solution is the least favorable).


Source: stackoverflow-php

Deploy the bitbucket code directly on production server

I am using the bitbucket to store our project. Now the problem is the project is very large and having more then 20k files in it. My server having FTP connection so i am not able to copy and paste the complete project code on server. So i want to direct deploy my code from bitbucket to my production server.

I can connect to the bitbucket server and make a git pull but i really want to find something to automate this.

I am looking for a easy and fast solution but i did not find anything for bitbucket, all solution seems to be designed for github…

Any service or tool for that to automate this process ?


Source: stackoverflow-php

Laravel Dompdf set starting page number

How can i set the starting page number? this is my code in dompdf:



    if (isset($pdf)) {
        $pdf->page_script('
             if ($PAGE_COUNT > 1) {

                $font = $fontMetrics->getFont("TimesNewRoman", "regular");                    
                $pdf->page_text(515, 50, "{PAGE_NUM}", $font, 11, array(.5,.5,.5));

            }
        ');
   }

if i want to set the value of {PAGE_NUM} to start in the number 10.


Source: stackoverflow-php

Calling Laravel Routes hosted on AWS Lambda using AWS API Gateway

I am trying to host a laravel application on aws lambda and call it’s routes using aws api gateway. The application is basically a web crawler which fetches web pages from rss feeds.

When I make a call to a laravel route using the url generated by api gateway, laravel redirects the request to ‘/home’ path. However, when I test it on ec2 instance using “node debug” , it works like a charm. Below are the details of the steps I followed.

I followed a fantastic blog written by Chris White for hosting a laravel application on aws lambda.

Steps:

  1. Generating a PHP CGI Binary

    I used “amzn-ami-hvm-2016.03.3.x86_64-gp2” ec2 instance to build my php-cgi binary file

./configure –prefix=/tmp/php-7.0.11/compiled/ –without-pear
–enable-shared=no –enable-static=yes –enable-phar –enable-json –disable-all –with-openssl –with-curl –enable-libxml –enable-simplexml –enable-xml –with-mhash –with-gd –enable-exif –with-freetype-dir –enable-mbstring –enable-sockets –enable-pdo –with-pdo-mysql –enable-tokenizer –enable-session –enable-filter

  1. NodeJS Lambda function to spawn PHP CGI process – php.js file

process.env['PATH'] = process.env['PATH'] + ':' + process.env['LAMBDA_TASK_ROOT'];

var parser = require('http-string-parser');
var spawn = require('child_process').spawn;
exports.handler = function(event, context) {

  var requestMethod = event.httpMethod || 'GET';
  var serverName = event.headers ? event.headers.Host : '';
  var requestUri = event.path || '';
  var headers = {};

  if (event.headers) {
    Object.keys(event.headers).map(function(key) {
      headers['HTTP_' + key.toUpperCase()] = event.headers[key];
    });
  }

  var request_env = Object.assign({
    REDIRECT_STATUS: 1,
    REQUEST_METHOD: requestMethod,
    SCRIPT_FILENAME: 'api/public/index.php',
    SCRIPT_NAME: '/index.php',
    PATH_INFO: '/',
    SERVER_NAME: serverName,
    SERVER_PROTOCOL: 'HTTP/1.1',
    REQUEST_URI: requestUri
  }, headers);

  var php = spawn('./php-cgi', ['api/public/index.php'], {
    env: request_env
  });

  var response = '';

  php.stdout.on('data', function(data) {
    response += data.toString('utf-8');
  });

  php.stderr.on('data', function(data) {
    console.log("STDERR: " + data.toString());
  });

  php.on('close', function(code) {

    var parsedResponse = parser.parseResponse(response);
    context.succeed({
      isBase64Encoded: false,
      statusCode: parsedResponse.statusCode || 200,
      headers: parsedResponse.headers,
      body: parsedResponse.body
    });

  });

}
  1. Prepare AWS Lambda bundle

    The directory structure of my HelloLambda.zip bundle is

├── api

├── node_modules

├── php-cgi

└── php.js

The api folder consists of my laravel application.

  1. API Gateway – I created a api gateway for my HelloLambda function. The api has league & channel as path parameters. The GET method uses lambda proxy integration. The api shows following url in stages view

https://***.execute-api.us-east-1.amazonaws.com/prod/HelloLambda/espnheadlinesimage/{league}/{channel}

api-gateway-screenshot.jpg

  1. Make a GET request to api providing the league and channel parameter.

https://***.execute-api.us-east-1.amazonaws.com/prod/HelloLambda/espnheadlinesimage/nhl/28

When I make this get request, the browser shows a message

Redirecting to http://***.execute-api.us-east-1.amazonaws.com/home

My laravel routes.php file consists of below route

Route::get('espnheadlinesimage/{league}/{channel}', 'EspnController@headlinesimage');

Any help would be highly appreciated. Thanks in advance.


Source: stackoverflow-php

Laravel 5.4 make:auth logging out in refresh or view change

So I have a problem which is very confusing.

I make authentication with php artisan make:auth. And I only change the controller in the router and the redirect in the LoginController as the documentation write. Before it is working perfectly but now it has a big problem. After I refresh the page or go to an other view it’s loout all the time.

I red a lot of stackoverflow question and answer but those not helped me out as well.


Source: stackoverflow-php

How to correctly nest where clause in laravel?

I’m looking to nest a where query inside a where query.

i want it to allways check if type is %Accu%.

$products = Product::where('type','LIKE', '%Accu%')
            ->where('beschrijving', 'LIKE','%'. $searchquery .'%')
            ->where('artikelcode','LIKE','%' . $searchquery . '%')
            ->where('prijs','LIKE','%' . $searchquery . '%')
            ->get();

I tried:

$products = Product::where('type','LIKE', '%Accu%', function($query) use ($searchquery) {
            $query->where('beschrijving', 'LIKE','%'. $searchquery .'%')->orWhere('artikelcode','LIKE','%' . $searchquery . '%')->orWherewhere('prijs','LIKE','%' . $searchquery . '%')->get();
        })->get();

Any help is appreciated


Source: stackoverflow-php

List all the users with the count of drivers they registered

i have tow models Userand Driver the user can register any number of drivers drivers

in drivers table i have agent_id, i want to list all the users with the count of the drivers they registered

in my Usercontroller i want to get the count of the drivers registered by the agents

public function index(Request $request) 
{
    $users = User::all();

    $registration_centers = RegistrationCenter::all();

    $drivers_registered = Driver::where('agent_id' , $agent_id)->count();  //something like this but i don't have agent_id to query with

    return view('agents', compact('users', 'registration_centers', drivers_registered));
}

thank you


Source: stackoverflow-php

How convert a data from database to html tags?

I have a table with description of my products, in there I have columns with html tags, when I get those data in modal, my data dont follow the html. I need convert that?

I’m using Laravel 5.4. When I pass the value directly, the tag is recognized.

My div

 
Descrição
{{$prod>description->erp_description}}

Any suggestion?


Source: stackoverflow-php

Laravel controller with modal bootstrap

I use Laravel Framework 5.4 and i need pass parameters from one button that open one Modal that receiving this parameters in myController and return data to myModal, somebody help me?

page1.blade.php

This button open my searchmodal.blade.php with jquery, it’s Right my href to call myController?

<a href="{{url('myController@search')}}" class="btn btn-success btnsearch">Search</a> 

jquery

    $('.btnsearch').click(function(e){
               $("#searchmodal").modal('show');
     })

myController need this parameters and return variables to get in Modal.

myController.php

public function search(parameter1){

  $customers = Customer::find(parameter1);

  //return my modal or page1?
   return view('searchmodal', compact('customers'));
}

mymodal.blade.php, how do i get the customers variable from myController?



Source: stackoverflow-php

second file downloads not first

I’ve got a problem when i’m dragging over my upload zone (drag n drop). For example, I have two files 1.csv, 2.csv and when i’m trying to upload this two files, only second uploads(2.csv). I want to upload just first and set permission to uploading only first file if two or more has chosen. Please help;(

    dropContainer.ondragover = dropContainer.ondragenter = function(evt) {
    evt.preventDefault();
};

dropContainer.ondrop = function(evt) {
    fileInput.files = evt.dataTransfer.files;

    evt.preventDefault();
};


Source: stackoverflow-javascript