Friday, March 30, 2018

After deleting the file for migration i am left with this message ‘Migration not found’ - development

After deleting the file for migration i am left with this message ‘Migration not found’

I have created by a mistake 2 migrations in my laravel project, using the php artisan make:migration command called 2018_03_30_075929_drop_products_tags_table and 2018_03_30_075242_create_products_tags_table and then i have deleted the files.

Now everything i run the command php artisan migrate:refresh I am get this error

Migration not found: 2018_03_30_075929_drop_products_tags_table
Migration not found: 2018_03_30_075242_create_products_tags_table
...

And i tried to run php artisan migrate:reset, but I am getting the same error. How can I fix this, because it is driving me insane 🙁



from Laravel Questions and Answers https://laravelquestions.com/php/after-deleting-the-file-for-migration-i-am-left-with-this-message-migration-not-found/
via Lzo Media

WordPress blog subdirectory with Laravel on nginx produces 404 error - development

WordPress blog subdirectory with Laravel on nginx produces 404 error

I installed a new WordPress blog thru Forge onto the same server as a Laravel 5.4 app. I put the blog in blog.example.com for simplicity sake, but I don’t have any DNS actually pointing to the subdomain. Instead, I want to have example.com/blog pointing to my WordPress installation.

I then modified the nginx conf file for the Laravel site to look like this:

# FORGE CONFIG (DOT NOT REMOVE!)
include forge-conf/example.com/before/*;

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name example.com;
    root /home/forge/example.com/current/public;

    # FORGE SSL (DO NOT REMOVE!)
    ssl_certificate /etc/nginx/ssl/example.com/230815/server.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com/230815/server.key;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'SHA-HASH-HERE';
    ssl_prefer_server_ciphers on;
    ssl_dhparam /etc/nginx/dhparams.pem;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.html index.htm index.php;

    charset utf-8;

    # FORGE CONFIG (DOT NOT REMOVE!)
    include forge-conf/example.com/server/*;

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

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;
    error_log  /var/log/nginx/example.com-error.log error;

    error_page 404 /index.php;

    location ~ .php$ {
        fastcgi_split_path_info ^(.+.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_read_timeout 600;
        fastcgi_send_timeout 600;
        fastcgi_connect_timeout 600;
        fastcgi_buffers 8 16k;
        fastcgi_buffer_size 32k;
    }

    location ~ /.(?!well-known).* {
        deny all;
    }

    location /blog {
        root /home/forge/blog.example.com/public;

        index index.php index.html index.htm;
        try_files $uri $uri/ /index.php?q=$uri&$args;

        access_log /var/log/nginx/blog.example.com-access.log;
        error_log /var/log/nginx/blog.example.com-error.log error;
    }
}

# FORGE CONFIG (DOT NOT REMOVE!)
include forge-conf/example.com/after/*;

I restarted nginx expecting to see the WP installation when I visit example.com/blog but instead I only see a 404 error from the Laravel app.

What is wrong with my approach here?



from Laravel Questions and Answers https://laravelquestions.com/laravel/wordpress-blog-subdirectory-with-laravel-on-nginx-produces-404-error/
via Lzo Media

Laravel blade with Vue component not show data - development

Laravel blade with Vue component not show data

I am using Laravel 5.6 and create model named process and a controller with a function that gets all the records of the model:

public function showProcessList(){
    return response()->json(Process::all());
}

In the web.php routes file also defined the route to retrieve the records, it works well, i tested the endpoint and i can see the data:

Route::get('process/list', 'ProcessController@showProcessList');

In a blade file i try to show the list creating a Vue component like this:

<!-- Process List -->
<div class="row">
<process></process>
</div>
<script src=''></script>

file app.js has this:

window.Vue = require('vue');

/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/

Vue.component('process', require('./components/Process.vue'));

const app = new Vue({
    el: '#app'
});

components/Process.vue contains this:

<template>     
   <div class="tile mb-4 col-md-6 col-lg-12" id="listProcess">
       <div class="page-header">
            <h3 class="mb-4 line-head">Process List</h3>
       </div>
       <div v-for="process in processList">
           <p></p>
       </div>
    </div>
</template>

<script>
    import axios from 'axios';

    export default {
        data () {
            return {
                processList: [],
            }
        },

    created() {
       this.showProcessList();
    },

    methods: {
        showProcessList () {
            axios.get('/process/list')
            .then(response => {
               this.processList = response.body;
             });

        }
    },
 }
</script>

Then execute npm run dev and load in web browser the view that invoke the Vue component:

<div class="row">
    <process></process>
</div>
<script src=''></script>

(I have to add public folder to the path of css and js files)

nothing happens, the data doesn’t load in the view and i cannot see any error in console.

Testing the endpoint the result is:

[
  {
    "id": 1,
    "created_at": "2018-03-28 04:33:02",
    "updated_at": "2018-03-28 04:33:02",
    "name": "first_process",
  },
]

So, at this point i cannot see where is the error in my code or what i missing?

Thanks.



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-blade-with-vue-component-not-show-data/
via Lzo Media

JSON Object returned with error from LARAVEL API not readable in Nodejs - development

JSON Object returned with error from LARAVEL API not readable in Nodejs

I am using Laravel apis for my project. The API is working fine when I use curl to access it.

curl -H "Content-Type: application/json" -X POST -d '{"username":"xyz","password":"xyz", "filterZip":"123123"}' http://localhost:8080/api/signup {"error":{"message":"User with specified email address already started sign up process, but did not finished it. Please sign in regulary to continue sign up process.","errorCode":"020102"}}

However when I call if from nodejs app. I am unable to access the error Json Object from the response.

From Nodejs I am calling my laravel API

fetch(API_URI + '/signup', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestBody)
    })

On the Laravel API end following code is used to return response.

public function respondError($errorId, $statusCode, $message = 'Unknown') {
        $this->setHttpStatusCode($statusCode);
        $errorCode = ErrorHelper::generateErrorCode($this->controllerErrorId, $this->methodErrorId, $errorId);
        if (API_LOG_ERROR_CODES) { ErrorHelper::logErrorCode($errorCode, $message); }

        return $this->respond([
            'error' => [
                'message' => $message,
                'errorCode' => $errorCode
                ]
        ]);
    }

public function respond($dataForJson, $headers = []) {

        return response()->json($dataForJson, $this->getHttpStatusCode(), $headers);
    }



from Laravel Questions and Answers https://laravelquestions.com/php/json-object-returned-with-error-from-laravel-api-not-readable-in-nodejs/
via Lzo Media

"405 Method not allowed" in Laravel 5.6.14 - development

"405 Method not allowed" in Laravel 5.6.14

I am just learning laravel resource methods to build a basic API. Below is the code of my api.php file that shows all the API routes.

// List Articles
Route::get('articles', 'ArticleController@index');

// List Single Article
Route::get('article/{id}', 'ArticleController@show');

// Create New Article
Route::post('article', 'ArticleController@store');

// Update Article
Route::put('article', 'ArticleController@store');

// Delete Article
Route::delete('article/{id}', 'ArticleController@destroy');

This works perfectly on get and delete methods. But for Post method, it is throwing error “405 Method not allowed”. I am using Postman to test the API calls.

To be specific, below is the exact error Postman shows

Symfony  Component  HttpKernel  Exception  MethodNotAllowedHttpException

Also attaching screenshot of Postman
enter image description here



from Laravel Questions and Answers https://laravelquestions.com/php/405-method-not-allowed-in-laravel-5-6-14/
via Lzo Media

Laravel Spark – Settings views not working - development

Laravel Spark – Settings views not working

Upgraded to version 6. Having lots of problems. None of the new views or assets wrote to the folders they were supposed to. Tried deleting what was there and reinstalling and it still didn’t work. I had to copy them over by hand and maybe I missed something because the settings items don’t work properly.

The menu on the left doesn’t function properly.
Plans are downloaded, but not shown in the subscriptions.
Errors occur when I try to look at teams or switch teams.

I made a short video to show the problems. Anything would help at this point. I have been slogging through this update for over a week…

Could this be an issue with the vue or with bootstrap 4 not loading properly?



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-spark-settings-views-not-working/
via Lzo Media

extract values from a method Laravel - development

extract values from a method Laravel

I have to add columns to a collection based on a common key …

$usersDatas = $users->each(function ($record) use ($timeData) {
    $times = array_first($timeData, function ($value, $key) use ($record) {
            return $value['id'] === $record['id'];
    });

    $record['totalTime'] = $times['totalTime'];
    $record['spendTime'] = $times['spendTime'];
    $record['remainingTime'] = $times['remainingTime'];
    var_dump($record);
 });
 dd($usersDatas);

the dd($records) inside gives me the right result … but i can’t extract the results outside…

the dd($records) gives me :

array:17 [▼
  "id" => 1
  "ua_id" => 351
  "grade_id" => 584
  "metier_id" => 18
  "nom" => "XXX"
  "prenom" => "XXX"
  "matricule" => "XXX"
  "email" => null
  "datenaissance" => "XXX"
  "casque" => null
  "created_at" => "2018-01-30 09:59:32"
  "updated_at" => "2018-01-30 09:59:32"
  "deleted_at" => null
  "totalTime" => 240
  "spendTime" => 0
  "remainingTime" => 0
]

While dd($usersDatas) gives me this :

0 => array:14 [▼
    "id" => 1
    "ua_id" => 351
    "grade_id" => 584
    "metier_id" => 18
    "nom" => "XXX"
    "prenom" => "XXX"
    "matricule" => "XXX"
    "email" => null
    "datenaissance" => "XXX"
    "casque" => null
    "created_at" => "2018-01-30 09:59:32"
    "updated_at" => "2018-01-30 09:59:32"
    "deleted_at" => null
    "pivot" => array:5 [▶]

the 3 last fields are missing…

"totalTime" => 240
"spendTime" => 0
"remainingTime" => 0



from Laravel Questions and Answers https://laravelquestions.com/laravel/extract-values-from-a-method-laravel/
via Lzo Media

laravel query whereBetween doesn’t work [duplicate] - development

laravel query whereBetween doesn’t work [duplicate]

This question already has an answer here:

Here is my Laravel query.

$fromdate = '2018-04-09';
$todate = '2018-04-28';
$dt = array($fromdate, $todate);
return DB::table('leaves')
  ->select('leaveId')
  ->whereBetween('from', [$dt[0], $dt[1]])
  ->orWhereBetween('to', [$dt[0], $dt[1]])
  ->get();

my db rows

'11', 'ckkl;kghhjgkgvjkvvb,,kkkkhhhhh', '2018-03-29', '2018-04-21', '2018-04-22', 'Sam User', NULL, '2018-03-29 10:52:48', '2018-03-29 10:52:48', '2', '8', '1'
'10', 'pjp'', '2018-03-29', '2018-04-11', '2018-04-12', 'test user', NULL, '2018-03-29 10:50:28', '2018-03-29 10:50:28', '1', '8', '1'

It seems it doesn’t check the whereBetween clause. It only returns leaveId. Thanks for your suggestions.



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-query-wherebetween-doesnt-work-duplicate/
via Lzo Media

get data to show in angularjs - development

get data to show in angularjs

I will try to do this to show data in page, but it’s not working. Is it wrong with my source below?

  $scope.confirmCapnhat=function(id){
                if($scope.p_id!="" && $scope.dn_taoMoi!="")
                {
            //      $scope.myVar = !$scope.myVar;
                    $http.get(API+'diennuoc/capnhat/'+id).then(successCallback,errorCallback);
                    function successCallback(response){
                        console.log(response);
                        $scope.sodauDien=response.data.dn_sodauDien;
                        $scope.diennuoc=response;
                    };
                    function errorCallback(response){
                        $scope.sodauDien=0;
                        $scope.sodauNuoc=0;
                    };  
                }
                else
                alert('Chưa chọn phòng hoặc ngày lập!');

            }

And here is result when ran console.log(response).
enter image description here



from Laravel Questions and Answers https://laravelquestions.com/php/get-data-to-show-in-angularjs/
via Lzo Media

Do you have to update laravel every time laravel version updates? - development

Do you have to update laravel every time laravel version updates?

I'm currently on 5.6.11. Do I need to update to latest version? How would I do that?

submitted by /u/Vraz_
[link] [comments]



from Laravel Questions and Answers https://laravelquestions.com/rlaravel/do-you-have-to-update-laravel-every-time-laravel-version-updates/
via Lzo Media

Wednesday, March 28, 2018

Laravel 5.4 (1/1) MethodNotAllowedHttpException on DELETE method - development

Laravel 5.4 (1/1) MethodNotAllowedHttpException on DELETE method

Before anyone points that is a duplicate I have checked these questions – laravel 5.4 MethodNotAllowedHttpException in RouteCollection.php (line 251), (1/1) MethodNotAllowedHttpException among others.

My problem is that I have done all of the solutions to all of the above posted questions and none have solved my issue.

ProfileController

  <?php

namespace AppHttpControllers;

use AppUser;
use IlluminateHttpRequest;
use IlluminateDatabaseEloquentModel;
use IlluminateSupportFacadesDB;
use Auth;


class ProfileController extends Controller
{
    //

    public function show($name) {

        $user = User::whereName($name)->first();
        if ($user) {

            // User exists
            return view('profile')->withUser($user);
        } else {
            dd($user);
        }

    }


    public function destroy($id){          


        DB::table('users')->where('id', '=', $id)->delete();
        return redirect()->route('/'); 
        }


}

profile.blade

      <ul class="profile-hero-header-menu">

    <li><a class="button primary" href="#"><i class="fa fa-envelope" aria-hidden="true"></i> Request Changes</a></li>
    <li><a class="button success" href="#"><i class="fa fa-life-ring" aria-hidden="true"></i> Contact Support</a></li>
      <form action="/profile/{id}/delete" method="POST">
       
     <input type="hidden" name="_method" value="DELETE">
    <li><a class="button alert" href="" name="DELETE"><i class="fa fa-trash" aria-hidden="true"></i> Close Account</a></li>
   </form>
  </ul>

web

Route::delete('/profile/{id}/delete', 'ProfileController@destroy')->name('profile.destroy')->middleware('auth');

On user click “Close Account” throws an exception –enter image description here



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-5-4-1-1-methodnotallowedhttpexception-on-delete-method/
via Lzo Media

Can’t install plugin NFS on windows 10 (Laravel/Homestead/VirtualBox) - development

Can’t install plugin NFS on windows 10 (Laravel/Homestead/VirtualBox)

I’ve been trying to install NFS because Laravel/Homestead/VirtualBox so slow on Windows.
I tried to run

$ vagrant plugin install vagrant-winnfsd

but it responded
this

C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/win32/registry.rb:185:in `encode!’: code converter not found (UTF-16LE to Windows-1258) (Encoding::ConverterNotFoundError)

My Homestead path: C:UsersMyPCHomestead

registry.rb:185

I don’t know how to fix this, if you know any clues, please help. Thank you.

Full error:

MyPC@hangnm MINGW64 ~/Homestead (master)
$ vagrant plugin install vagrant-winnfsd
Installing the ‘vagrant-winnfsd’ plugin. This can take a few minutes…
C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/win32/registry.rb:185:in encode!': code converter not found (UTF-16LE to Windows-1258) (Encoding::ConverterNotFoundError)
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/win32/registry.rb:185:in
initialize’
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/win32/registry.rb:250:in exception'
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/win32/registry.rb:250:in
raise’
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/win32/registry.rb:250:in check'
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/win32/registry.rb:320:in
QueryValue’
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/win32/registry.rb:644:in read'
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/win32/resolv.rb:67:in
read_s’
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/win32/resolv.rb:101:in block in get_info'
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/win32/registry.rb:435:in
open’
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/win32/registry.rb:542:in open'
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/win32/resolv.rb:91:in
get_info’
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/win32/resolv.rb:21:in get_resolv_info'
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/resolv.rb:966:in
default_config_hash’
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/resolv.rb:983:in block in lazy_initialize'
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/resolv.rb:976:in
synchronize’
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/resolv.rb:976:in lazy_initialize'
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/resolv.rb:358:in
block in lazy_initialize’
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/resolv.rb:356:in synchronize'
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/resolv.rb:356:in
lazy_initialize’
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/resolv.rb:516:in fetch_resource'
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/resolv.rb:510:in
each_resource’
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/resolv.rb:491:in getresource'
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/rubygems/remote_fetcher.rb:105:in
api_endpoint’
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/rubygems/source.rb:47:in api_uri'
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/rubygems/source.rb:183:in
load_specs’
from C:/HashiCorp/Vagrant/embedded/gems/2.0.3/gems/vagrant-2.0.3/lib/vagrant/bundler.rb:351:in block in validate_configured_sources!'
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/rubygems/source_list.rb:98:in
each’
from C:/HashiCorp/Vagrant/embedded/mingw64/lib/ruby/2.4.0/rubygems/source_list.rb:98:in each_source'
from C:/HashiCorp/Vagrant/embedded/gems/2.0.3/gems/vagrant-2.0.3/lib/vagrant/bundler.rb:349:in
validate_configured_sources!’
from C:/HashiCorp/Vagrant/embedded/gems/2.0.3/gems/vagrant-2.0.3/lib/vagrant/bundler.rb:285:in internal_install'
from C:/HashiCorp/Vagrant/embedded/gems/2.0.3/gems/vagrant-2.0.3/lib/vagrant/bundler.rb:106:in
install’
from C:/HashiCorp/Vagrant/embedded/gems/2.0.3/gems/vagrant-2.0.3/lib/vagrant/plugin/manager.rb:62:in block in install_plugin'
from C:/HashiCorp/Vagrant/embedded/gems/2.0.3/gems/vagrant-2.0.3/lib/vagrant/plugin/manager.rb:72:in
install_plugin’
from C:/HashiCorp/Vagrant/embedded/gems/2.0.3/gems/vagrant-2.0.3/plugins/commands/plugin/action/install_gem.rb:29:in call'
from C:/HashiCorp/Vagrant/embedded/gems/2.0.3/gems/vagrant-2.0.3/lib/vagrant/action/warden.rb:34:in
call’
from C:/HashiCorp/Vagrant/embedded/gems/2.0.3/gems/vagrant-2.0.3/lib/vagrant/action/builder.rb:116:in call'
from C:/HashiCorp/Vagrant/embedded/gems/2.0.3/gems/vagrant-2.0.3/lib/vagrant/action/runner.rb:66:in
block in run’
from C:/HashiCorp/Vagrant/embedded/gems/2.0.3/gems/vagrant-2.0.3/lib/vagrant/util/busy.rb:19:in busy'
from C:/HashiCorp/Vagrant/embedded/gems/2.0.3/gems/vagrant-2.0.3/lib/vagrant/action/runner.rb:66:in
run’
from C:/HashiCorp/Vagrant/embedded/gems/2.0.3/gems/vagrant-2.0.3/plugins/commands/plugin/command/base.rb:14:in action'
from C:/HashiCorp/Vagrant/embedded/gems/2.0.3/gems/vagrant-2.0.3/plugins/commands/plugin/command/install.rb:32:in
block in execute’
from C:/HashiCorp/Vagrant/embedded/gems/2.0.3/gems/vagrant-2.0.3/plugins/commands/plugin/command/install.rb:31:in each'
from C:/HashiCorp/Vagrant/embedded/gems/2.0.3/gems/vagrant-2.0.3/plugins/commands/plugin/command/install.rb:31:in
execute’
from C:/HashiCorp/Vagrant/embedded/gems/2.0.3/gems/vagrant-2.0.3/plugins/commands/plugin/command/root.rb:66:in execute'
from C:/HashiCorp/Vagrant/embedded/gems/2.0.3/gems/vagrant-2.0.3/lib/vagrant/cli.rb:46:in
execute’
from C:/HashiCorp/Vagrant/embedded/gems/2.0.3/gems/vagrant-2.0.3/lib/vagrant/environment.rb:269:in cli'
from C:/HashiCorp/Vagrant/embedded/gems/2.0.3/gems/vagrant-2.0.3/bin/vagrant:151:in



from Laravel Questions and Answers https://laravelquestions.com/laravel/cant-install-plugin-nfs-on-windows-10-laravel-homestead-virtualbox/
via Lzo Media

need help for laravel: How i attach my disease table with others - development

need help for laravel: How i attach my disease table with others

I an new to Laravel.
i want when i store data that is storing correctly in multiple tables.
after storing it will also have the id of all three tables on disease_symptoms_medicines table( foreignkeys)
i not know how to do it.
help me!!!
In this code there is no error (if error due to poor english and typing mistakes)

here is my migrations

<?php

    use IlluminateSupportFacadesSchema;
    use IlluminateDatabaseSchemaBlueprint;
    use IlluminateDatabaseMigrationsMigration;

    class CreateDiseasesTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('diseases', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name')->nullable();
                $table->string('slug')->nullable();
                $table->text('description')->nullable();
                $table->text('symptoms')->nullable();
                $table->timestamps();
            });
        }

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

symtom migration

public function up()
{
    Schema::create('symptoms', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

Medicine migration

public function up()
{
    Schema::create('diseases', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name')->nullable();
        $table->string('slug')->nullable();
        $table->text('description')->nullable();
        $table->text('symptoms')->nullable();
        $table->timestamps();
    });
}

created for foreign keys to attach Disease,Symptoms and Medicine

Disease Model

    class Disease extends Model
    {
protected $table ='diseases';
public function symptoms(){

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

    return $this->belongsTo('AppMedicine');
}

Symtom Model

    class Symptoms extends Model{
    protected $table ='symptoms';
    public function diseases()
    {
    return $this->hasMany('AppDisease');
}

}

Medicine Model

    class Medicine extends Model{
    protected $table ='medicines';
    public function diseases(){

    $this->hasMany('AppDisease');
}
}

here is my controller

    public function store(Request $request)
{
    $disease=new Disease;
    $disease->name=$request->input('name');
    $disease->slug=$request->input('slug');
    $disease->description=$request->input('description');
    $disease->save();
    $symptom=new Symptoms;
    $symptom->name=$request->input('symtom');
    $symptom->save();
    $medicine=new Medicine;
    $medicine->name = $request->input('medic');
    $$medicine->save();

    return redirect()->back();
}

i want when i store data that is storing correctly in multiple tables.
after storing it will also have the id on disease_symptoms_medicines table( foreignkeys)
i not know how to do it.
help me!!!



from Laravel Questions and Answers https://laravelquestions.com/php/need-help-for-laravel-how-i-attach-my-disease-table-with-others/
via Lzo Media

Seeding in laravel for multiple databases - development

Seeding in laravel for multiple databases

I am working on a school project with multiyear database built in laravel.
My requirement is to feed data for every new academic year in some tables. I have a main(superadmin) db and separate school’s db for every school. I need to connect to school db, n process is i have kept superadmin db details in .env file then it fetches particular school’s db details and makes a connection to that school db through middleware.
My question is when i executes migration and seeding command it connects to superadmin db and performs respective operation on same. But i want to execute migration/seeding one by one for every school’s db.
Please provide suggestions. Thank you.



from Laravel Questions and Answers https://laravelquestions.com/laravel/seeding-in-laravel-for-multiple-databases/
via Lzo Media

Korean characters become "???" after exported using dompdf laravel - development

Korean characters become "???" after exported using dompdf laravel

I using dompdf for laravel, the problem is the Korean characters can show properly in html but it’s turn into “???” when exported into pdf.

Korean characters in header and footer can show properly using $canvas->page_script() but Korean characters in loadHTML not showing properly.

Can someone help me?

        $pdf->loadHTML($doc_content);
        $pdf->output();
        $dom_pdf = $pdf->getDomPDF();
        $options = new Options();
        $options->set('isPhpEnabled', true);
        $options->set('isRemoteEnabled', true);
        $options->set('defaultFont', 'UnShinmun');
        $dom_pdf->setOptions($options);
        $canvas = $dom_pdf->get_canvas();
        //$canvas->page_text(0, 0, "Page {PAGE_NUM} of {PAGE_COUNT}", null, 10, array(0, 0, 0));

        $canvas->page_script('              
            $font = $fontMetrics->get_font("UnShinmun");
            $size = 11;

            $pageText = "'.$doc_title.'";
            $y = 30;
            $x = $pdf->get_width()-30- $fontMetrics->get_text_width($pageText, $font, $size);
            $pdf->text($x, $y, $pageText, $font, $size, array(.302, .302, .302));

            $pageText = "'.$doc_num.'";
            $y = 44;
            $x = $pdf->get_width()-30- $fontMetrics->get_text_width($pageText, $font, $size);
            $pdf->text($x, $y, $pageText, $font, $size, array(.302, .302, .302));

            $size = 9;

            $pageText = "Page " . $PAGE_NUM. " of " . $PAGE_COUNT;
            $y = $pdf->get_height() - 38;
            $x = $pdf->get_width()-30- $fontMetrics->get_text_width($pageText, $font, $size);
            $pdf->text($x, $y, $pageText, $font, $size, array(.302, .302, .302));

            $pageText = "'.($type=='Form'?'':'Version No.: 01').'";
            $y = $pdf->get_height() - 38;
            $x2 = 28;
            $pdf->text($x2, $y, $pageText, $font, $size, array(.302, .302, .302));

            $y = $pdf->get_height() - 24;
            $pageText = "V' . '1.00' . '";
            $pdf->text($x, $y, $pageText, $font, $size, array(.302, .302, .302));               
            $pdf->line(28,795,567,795,array(.302, .302, .302),1); #footer hr
       ');
        //$pdf->render();
        $output = $pdf->output();



from Laravel Questions and Answers https://laravelquestions.com/laravel/korean-characters-become-after-exported-using-dompdf-laravel/
via Lzo Media

Calculated column in Laravel to transform name in slug - development

Calculated column in Laravel to transform name in slug

I have a Location Model and Migration. Here I have name. Now I want to add an extra column (calculated), that will be name column with some replacement of special characters, and spaces to -. I will write that replace function by myself. I can’t find a way of introducing calculated columns.
Thanks.



from Laravel Questions and Answers https://laravelquestions.com/php/calculated-column-in-laravel-to-transform-name-in-slug/
via Lzo Media

Modifying Laravel’s Generated Registration Logic - development

Modifying Laravel’s Generated Registration Logic

So, I am still kind of a newbie to Laravel. As part of the application I am working on, I want to modify the registration logic generated by

php artisan make:auth

to add e-mail verification for newly registered users.

I modify the create() method on the generated RegisterController to look like this.

 protected function create(array   $data)
  {
      $user = User::create([

        'name' => $data['name'],

        'email' => $data['email'],

        'password' => Hash::make($data['password']),
    ]);

    // generate and store verification token

    $token = new Token; 
    $token->user_id = $user->id; 
    $token->token = str_randome(40); 
    $token->save(); 
    // send a verification e-mail to the 
    $this->sendVerificationEmail($user->id); 

    return $user;
}

So, on to my question. Suppose I want to capture the returned user on the verification page (which is assigned to the $redirectTo property) so that the application knows to which user to resend the e-mail if said user requests it be resent. What is the best way to achieve this?

Should I just create a new route like this

 // Routes/web.php

Route::post(‘register/{$user}’, ‘RegisterController@showConfirmation’);

And then in my RegisterController

// RegisterController
public function showConfirmation($user)
{ return view(“accountConfirmation”)->([“user”=> $user]);}

Or is there another way? I guess the route of my problem here is that I don’t quite yet understand how Laravel performs this process. But, anyways.

Thanks for the help.



from Laravel Questions and Answers https://laravelquestions.com/php/modifying-laravels-generated-registration-logic/
via Lzo Media

Want to show name as a parameter instead of id in the URL field in Laravel - development

Want to show name as a parameter instead of id in the URL field in Laravel

I don’t want to show /route_name/{id} in the URL field of my Laravel project. Instead of that I want to show /route_name/{name} and also pass the id in the back-end to the controller.

Suppose I have a view department.blade.php. Now click on knee pain from the menubar for seeing the details. Here is my view code

<a href=">
   
</a>"

After click the knee pain a route called. Here is the route

Route::get('/home_services_under_department/{id}', 'frontendDepartmentController@home_services_under_department');

Here is the home_services_under_department method format

public function home_services_under_department($id){}

Here is my URL in browser
http://url/home_services_under_department/2

But I don’t want to see the id after home_services_under_department, I want to see the name knee-pain after home_services_under_department as a parameter like

http://url/home_services_under_department/knee-pain 

and also want to pass the id to the controller method.

Is it possible in Laravel ?



from Laravel Questions and Answers https://laravelquestions.com/php/want-to-show-name-as-a-parameter-instead-of-id-in-the-url-field-in-laravel/
via Lzo Media

one to many relationship laravel - development

one to many relationship laravel

I am making a one to many relationship, when I try to save it, it asks me to enter the FK should not I do it automatically?

class AlternativesCompetitorsImage extends Model
{
    public function alternativecompetitors()
    {
        return $this->belongsTo(AlternativesCompetitor::class,'id');
    }
}



class AlternativesCompetitor extends Model
{

    public function alternativescompetitorsimages(){
        return $this->hasMany(AlternativesCompetitorsImage::class,'alter_comp_id');
    }
}

Controller

$ci = isset($id_image) ? $step->alternativescompetitorsimages :  new AlternativesCompetitorsImage();

        if( $request->hasFile('fileImg')){
            $fileRequests = request()->file('fileImg');
            $count = 0;
            foreach ($fileRequests as $fileRequest) {
            $keyCanvas = $c->key;
            $stepKey = $stepType->key;
            $public= public_path();
            $directory =DIRECTORY_SEPARATOR."canvas".DIRECTORY_SEPARATOR.$keyCanvas.DIRECTORY_SEPARATOR.$stepKey;
            $newName = "image".$count.".png";
            Storage::deleteDirectory($directory);
            $path = $fileRequest->storeAs("public".$directory,$newName);
            $str = str_replace("", '/', $path);
            $ci->url_img = $str;
             !isset($id_image) ? $step->alternativescompetitorsimages()->save($ci) : $step->alternativescompetitorsimages()->update($ci->toArray());           
            DB::commit();
            $count++;
            }

Migrations

class CreateAlternativesCompetitorsImages extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
         Schema::create('alternatives_competitors_images',function(Blueprint $table){
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('url_img',100);
            $table->integer('alter_comp_id')->unsigned();            
            $table->timestamps();


            $table->foreign('alter_comp_id')->references('id')->on('alternatives_competitors');
            });
    }


class CreateAlternativesCompetitors extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('alternatives_competitors',function(Blueprint $table){
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->integer('step_id')->unsigned();
            $table->string('valueA',10);
            $table->string('valueB',10);
            $table->timestamps();

            $table->foreign('step_id')->references('id')->on('steps');
            });
    }

Next IlluminateDatabaseQueryException: SQLSTATE[23000]: Integrity
constraint violation: 1048 Column ‘alter_comp_id’ cannot be null (SQL:
insert into alternatives_competitors_images (url_img,
alter_comp_id, updated_at, created_at) values
(public/canvas/de939a01-1438-4aff-bb23-eb4f68653f5f/TEAM/image0.png, ,
2018-03-27 23:31:12, 2018-03-27 23:31:12)) in
C:xampphtdocscanvasvendorlaravelframeworksrcIlluminateDatabaseConnection.php:647



from Laravel Questions and Answers https://laravelquestions.com/php/one-to-many-relationship-laravel/
via Lzo Media

What is the most appropriate way to debug your source code in Laravel? - development

What is the most appropriate way to debug your source code in Laravel?

An error message should speak about the cause. Least it should be convenient for the developer to track a the bug with some hints(like the name of file, a function, either in controller or model, or both or the view, etc.)

What about Laravel?

This is not the first time, there comes an issue almost everyday in the code(of course we love bugs, we’ll learn from it). What if you spend the whole day tracking a typo err? What if there is only a black board saying:

Better luck next time!!*

By default, the happiest framework is the ever worse to give accurate errors in the code. May be there is a method, may be that is what this question asks about.

php artisan r:l

[SymfonyComponentDebugExceptionFatalErrorException]

Fatal error: Namespace declaration statement has to be the very first
statement ..

.. so that says where the error is. Check all the Controllers & Models to find the the exception. That will only waste the time and still the same error. The server was started early morning and still running. Browser is working but not loading the page. This must have happened because of a recent change in a file but not sure exactly which one.

Another day, another one:

TokenMismatchException in VerifyCsrfToken …

So far I know of 5 possible cases that will lead to this error. Not going to list em’ all. Almost every time it only kills my time, at the end I realize it was not worth 5 mins.

————————————————————————–

  • Now what is the solution? How is it possible to track such an bug
    with the Laravel core tools? In other way, how is it possible for a
    Laravel5 website to show accurate errors?
  • How could I handle exceptions in Laravel? Which file(class) may help
    me to work on it if I wish to arrange such a platform (that always
    tells me what/where exactly the problem is) before I start working on
    a fresh L5 copy?
  • I started from Laravel v5.2 only. Hope there won’t be much difference
    in other earlier and later versions. What about them?
  • And most importantly, how is it possible to track errors from the console
    while the server is running in the background? Any php artisan ..
    command(s)?

[After dinner I found the bug(Namespace declaration) was with a route that spelled wrong and so was not redirecting to the proper view from the controller! BAD TYPO]



from Laravel Questions and Answers https://laravelquestions.com/php/what-is-the-most-appropriate-way-to-debug-your-source-code-in-laravel/
via Lzo Media

Monday, March 26, 2018

Webpack outputs wrong image path - development

Webpack outputs wrong image path

I’m using Webpack/Laravel Mix. On my original Sass file, a certain path looks like this:

.is-gplay {
  background-image: url(../images/bcg/gplay.png);
}

Mix and webpack will then find the image and copy it to public/images. It will also rewrite the path within the new css file to

.is-gplay {
  background-image: url(/images/gplay.png?d1b4cc17fbb3149178c9a1a6a47e33f);
}

Great. Except it copied the picture to public/images and wrote a path to public/css/images, so now the browser won’t find it unless I edit my compiled css and add ../ in front of the image path so it sees the images folder is outside the css folder by default.

What am I missing here? Why does it create an images folder outside the css folder and then writes a path to css/images?

Sorry if this is something simple I’m not realizing right now. It’s my first time working with webpack.



from Laravel Questions and Answers https://laravelquestions.com/laravel/webpack-outputs-wrong-image-path/
via Lzo Media

How do i Insert information to Order-OrderProduct tables MySQL Laravel - development

How do i Insert information to Order-OrderProduct tables MySQL Laravel

I am developing simple e commerce website with laravel for learning purposes.

There are few things confusing me about database relations and inserting data to order-order_product tables when customer places an order.

User Migration:

Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('address');
            $table->string('phone');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

User Model:

class User extends Authenticatable
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $attributes =[
     'street' => 'no adress entered',
     'city' => 'no city entered',
     'phone' => 'no phone'


    ];
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
    public function orderproduct(){        
        return $this->hasMany('AppOrderProduct');   
}
}

Orders Table:

 Schema::create('orders', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('customer_id')->unsigned();
            $table->foreign('customer_id')->references('id')->on('users');
            $table->string('name');
            $table->string('address');
            $table->string('phone');
            $table->date('order_date'); 

            $table->timestamps();
        });

Order Model:

class Order extends Model
{
   //Table Name

   protected $table = 'orders';

   //Primary Key

   public $primaryKey = 'id';

   //Timestamps

   public $timestamps =true;

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

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

}

Products Table:

Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('img');
            $table->string('name');
            $table->string('desc');
            $table->integer('quantity');//stokta kaç tane oldugu
            $table->integer('price');
            $table->timestamps();
        });

Product Model:

    class Product extends Model
{

    //Table Name

    protected $table = 'products';

    //Primary Key

    public $primaryKey = 'id';


    //Timestamps

    public $timestamps =true;

    public function orderproduct(){        
        return $this->belongsTo('AppOrderProduct');

    }
}

order_product Table:

 Schema::create('order_product', function (Blueprint $table) {
            $table->increments('id');
              $table->integer('order_id')->unsigned();
            $table->integer('product_id')->unsigned();
            $table->integer('quantity')->unsigned();
            $table->timestamps();

            $table->foreign('order_id')->references('id')->on('orders');
            $table->foreign('product_id')->references('id')->on('products');
        });

OrderProduct Model:

class OrderProduct extends Model
{

    //Table Name

    protected $table = 'order_product';

    //Primary Key

    public $primaryKey = 'id';


    //Timestamps

    public $timestamps =true;

public function order(){         
    return $this->belongsTo('AppOrder');   

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

}



}

I am using laravel session to hold cart data.Also i have a ordercontroller for storing order to database.
The question is how do i insert correctly to order and order_product tables? First am i going to insert to orders then to order_product table ? For example if user has multiple items in his cart because product_id column in order_product table needs to be atomic i need to insert multiple rows.
I can access product_id and their quantity from my cart but i couldnt manage to loop them properly and insert to db.

public function store(Request $request)
    {
        $oldCart = Session::get('cart'); 
        $cart = new Cart($oldCart);
//dd(arrays_keys($cart->items)); // returns ids of products in cart
//dd($cart->items[1]['qty']);      // returns quantity of item which has id 1



        $order = new Order;
        $order->name = $request->input('name');
        $order->address = $request->input('address');
        $order->phone = $request->input('phone');
        $order->customer_id = auth()->user()->id;

        $order->save();

        $orderProduct = new OrderProduct;

        //$orderProduct->product_id = ??  how to write in multiple rows if user has multiple items(so values will be atomic in product_id column)
        //$orderProduct->quantity= ??



    }



from Laravel Questions and Answers https://laravelquestions.com/laravel/how-do-i-insert-information-to-order-orderproduct-tables-mysql-laravel/
via Lzo Media

PHP Laravel Gallery split array into 3 columns - development

PHP Laravel Gallery split array into 3 columns

I’m would like to have this effect:

<div class="w3-third">
    Images tags here
</div>
<div class="w3-third">
    Images tags here
</div>
<div class="w3-third">
    Images tags here
</div>

I have this php code:

$images = Image::where('gallery_id', $id)->get();

$list = [];
foreach ($images as $image) {
    array_push($list, $image->file_path);
}
$list = array_chunk($list, 3);

return view('gallery.gallery')
->with([
    'gallery' => $gallery,
    'images' => $list
]);

And i want to push images from this list into those 3 columns.



from Laravel Questions and Answers https://laravelquestions.com/php/php-laravel-gallery-split-array-into-3-columns/
via Lzo Media

Laravel get array of filenames from folder - development

Laravel get array of filenames from folder

I am getting an array of filenames from a folder like this…

$files = File::allFiles('myfolder/');

But the resulting array contains pathname as well.

Is there a way of just getting an array of filenames? Or do I need to process each array item and extract the filename from it?



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-get-array-of-filenames-from-folder/
via Lzo Media

Laravel seeding via SQL file - development

Laravel seeding via SQL file

I’m trying to read data from a .sql file in a seeder to fill 3-4 tables with some data and DatabaseSeeder.php looks like this

public function run() {
    $this->call([
        UsersTableSeeder::class,
        // Bunch of seeders using Eloquent
        SqlSeeder::class
    ]);
}

All other seeders execute and, actually, when trying to throw an exception in SqlSeeder.php I’m able to stop the seeding. However, SqlSeeder.php won’t seed the database via php artisan migrate:fresh --seed, seems like it’s bypassed. I always need to run php artisan db:seed --class SqlSeeder after, in order to make it seed the database. SqlSeeder.php looks like this

public function run() {
    $path = base_path().'/database/seeds/sql/data.sql';
    $sql = file_get_contents($path);
    DB::unprepared($sql);
}

Why’s that?



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-seeding-via-sql-file/
via Lzo Media

Create a Plugin System in Laravel CMS project - development

Create a Plugin System in Laravel CMS project

Hello laravel developers,

this is first post for me and hope someone help me in my issue.

I developing CMS by laravel 5.5 and i have 3 main module as follow:

  • layout (in this module i define my layout [rows + cols] and then inject plugin please have look to below image). layout
  • post/page in this module i choose one of my layout that i have created, also it should call plugin that existing in attached layout.
  • i will store my plugin as blade template Plugin>main-content.balde.php

Problem:

now when page or post opening i want to load the layout and mapping the plugin and i want to do this automatically without (if or else) statement
layout design

Idea:

one of idea i have to use view composer but as you see the name of plugin will be loaded from database and of course it will be changed regarding to layout.

sec idea to use laravel package, design plugin as package

third, create helper function and will be loaded in layout and this function will do the mapping but, here is the important question can i do helper function that connect directly to model without controller ?



from Laravel Questions and Answers https://laravelquestions.com/php/create-a-plugin-system-in-laravel-cms-project/
via Lzo Media

How to get access to relationship in model User Laravel? - development

How to get access to relationship in model User Laravel?

I have default User model:

class User extends Authenticatable implements HasRoleContract
{
    use Notifiable, HasRole;

}

With one relationship inside:

public function distributor() {

    return $this->hasOne('AppDistributorContacts', 'distributor_id', 'id');
}

So, when user passed authorization I can not see this relation in object:



enter image description here



from Laravel Questions and Answers https://laravelquestions.com/laravel/how-to-get-access-to-relationship-in-model-user-laravel/
via Lzo Media

Laravel 5.5 – Transfer file to S3 - development

Laravel 5.5 – Transfer file to S3

I have an array of filenames that looks like this

array (
'file1.jpg',
'file2.jpg',
'file3.jpg'
)

I am trying to loop through them and upload them to an S3 bucket like this..

foreach ($filenames as $filename) {
    Storage::disk('s3')->put(

        /* S3 */
        's3foldername/' . $foldername . '/' . $filename,

        /* Local Storage */
        storage_path('localfolder/' . $foldername . '/' . $filename),
        'public'
    );
}

This isn’t working for some reason, the paths all check out ok. Do I need to read the file contents first?



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-5-5-transfer-file-to-s3/
via Lzo Media

How to install a github repo with composer and user it in laravel ? - development

How to install a github repo with composer and user it in laravel ?

https://github.com/abhinayrathore/PHP-IMDb-Scraper

I'm looking to use the above package in a project, could someone give me a quick tip on how to install it with composer .

thank you

submitted by /u/eid-a
[link] [comments]



from Laravel Questions and Answers https://laravelquestions.com/rlaravel/how-to-install-a-github-repo-with-composer-and-user-it-in-laravel/
via Lzo Media

Laravel or Joomla [on hold] - development

Laravel or Joomla [on hold]

I am in the process of building a CRM, I would like to add functionalities like real-time reports, real-time graphs, notifications to customers and admins, API functionality to the CRM so other web services can connect to my app, be able to easily add new features or Modules and the most important thing build it so other developers can easily make changes or adds.

thank you all.



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-or-joomla-on-hold/
via Lzo Media

Sunday, March 25, 2018

Laravel 5 mail not sending… - development

Laravel 5 mail not sending…

I've been at this for a few hours now, and I'm giving up. Ruined my Sunday in fact…

I've got an app – it sends mail perfectly through Gmail, but I wanted it to send through my domain, so I ordered business email from Namecheap and thought it would be simple enough. It's not.

I'm using the same exact info and credentials in my .env file as I am in my desktop mail client. Copied and pasted. My desktop sends. My server reports the email address as having failed.

Switch the credentials and point them at Mailtrap, and again, it works fine.

I'm not seeing anything about this failure anywhere in any of my log files, so I have no idea where to even start debugging.

Oh, and i checked with Namecheaps customer service, but they reported everything is standard on their end.

Has anyone got experience with Laravel and Namecheaps email service? I'm to the point now that I just want to use PHPMailer, but that's silly since Laravel has a mailer built in.

Any tips or pointers would be HIGHLY appreciated! Thanks!

submitted by /u/identicalBadger
[link] [comments]



from Laravel Questions and Answers https://laravelquestions.com/rlaravel/laravel-5-mail-not-sending/
via Lzo Media

First foreach statement in if statement not initiating, skips straight to second one? - development

First foreach statement in if statement not initiating, skips straight to second one?

So I am having an issue. I have two if statements that request-> data from the form. However, when I have both checked, it is skipping over the first one and going to the second one. The foreach statements in the first one do not even initiate and I have no idea why.

Here is my code:

if ($request->location_verification == 'on') {
    $get_data = [];
    foreach (array_chunk($results, 50) as $chunk_result) {
        foreach ($chunk_result as $r) {

            $client_name = trim($r['first_name'] . ' ' . $r['last_name']);
            if ($client_name == '') {
                $check_name = ContactList::where('phone_number', $r['phone_number'])->first();
                if ($check_name) {
                    $client_name = trim($check_name->first_name . ' ' . $check_name->last_name);
                    if ($client_name == '') {
                        $client_name = 'no name';
                    }
                } else {
                    $client_name = 'no name';
                }
            }
            $client_name = urlencode($client_name);

            $url = url('user/get-location/' . Auth::guard('client')->user()->id . '/' . $r['phone_number'] . '/' . $client_name);
            $get_message = $message . "n" . $url;
            $r = array_merge($r, ['message' => $get_message]);
            array_push($get_data, $r);
        }
    }
} else {
    $get_data = $results;
}


if ($request->attachment_tracking == 'on') {
    $get_data = [];
    $lastMessage = MessageFiles::orderBy('message_id', 'desc')->first();
    if ($files = $request->file('files')) {
        if ($first == true) {
            if (count($lastMessage) >= 1) {
                $messageCount = $lastMessage->message_id + 1;
            } else {
                $messageCount = 1;
            }
            foreach ($files as $f) {
                $destinationPath = public_path() . '/assets/message_files/';
                $file_name = $f->getClientOriginalName();
                $extension = $f->getClientOriginalExtension();
// Available alpha caracters
                $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

// generate a pin based on 2 * 7 digits + a random character
                $pin = mt_rand(1000000, 9999999)
                    . mt_rand(1000000, 9999999)
                    . $characters[rand(0, strlen($characters) - 1)];

// shuffle the result
                $string = str_shuffle($pin);
                $f->move($destinationPath, $string . '.' . $extension);


                $tf = new MessageFiles();
                $tf->message_id = $messageCount;
                $tf->cl_id = Auth::guard('client')->user()->id;
                $tf->message = $get_message;
                $tf->file = $string . '.' . $extension;
                $tf->save();
                $first = false;
            }
        }
        foreach (array_chunk($results, 50) as $chunk_result) {
            foreach ($chunk_result as $r) {

                $client_name = trim($r['first_name'] . ' ' . $r['last_name']);
                if ($client_name == '') {
                    $check_name = ContactList::where('phone_number', $r['phone_number'])->first();
                    if ($check_name) {
                        $client_name = trim($check_name->first_name . ' ' . $check_name->last_name);
                        if ($client_name == '') {
                            $client_name = 'no name';
                        }
                    } else {
                        $client_name = 'no name';
                    }
                }
                $client_name = urlencode($client_name);

                $url = url('user/get-attachment/' . Auth::guard('client')->user()->id . '/' . $r['phone_number'] . '/' . $client_name);
                $get_message = $message . "n" . $url;
                $r = array_merge($r, ['message' => $get_message]);
                array_push($get_data, $r);
            }
        }
    } else {
        return redirect('user/sms/add-recurring-sms')->withInput(Input::all())->with([
            'message' => "No uploaded files found. Please upload a file to use attachment tracking.",
            'message_important' => true
        ]);
    }
}

Basically, location_verification is being run but the foreach statement is not.
Then when attachment_verification is run, the foreach (array_chunk runs perfectly but it doesn’t in location_verification.

I tried switching them around and the first foreach(array_chunk never runs. Could it be because of similar values?

I am super lost.

EDIT: array_push is not happening and the new message is not being updated for the first if statement.



from Laravel Questions and Answers https://laravelquestions.com/php/first-foreach-statement-in-if-statement-not-initiating-skips-straight-to-second-one/
via Lzo Media

filter charts with laravel - development

filter charts with laravel

I need to develop dashboard with laravel as demo
https://jtainslie.github.io/crossfilter-demo/
but I didn’t find chart packages that filters when click on part of chart
can you help me please?



from Laravel Questions and Answers https://laravelquestions.com/laravel/filter-charts-with-laravel/
via Lzo Media

Laravel Url two levels deep - development

Laravel Url two levels deep

Learning Laravel, I have set up a dev area on AWS with an Ubuntu server. I can create pages that are one level deep

Route::get('/campgrounds','CampgroundController@index');

these work fine but when I go two levels deep they don’t work. When I try to create a route that is two levels deep I get a “that page your looking for doesn’t exist”.

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

});

I don’t see anything in the logging.log file that is erring out. Is there a Laravel setting I need or setting on Apache that needs changing? Maybe something in the .env file?



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-url-two-levels-deep/
via Lzo Media

Laravel Replace Unicode Characters in Database - development

Laravel Replace Unicode Characters in Database

I stored some hours from Google Places and little did I know it brought in some longer dashes (u2013) and I’d like to loop through and convert anything in the database that is a unicode string into a normal string, as when I retrieve these hours I can’t explode them via

explode(' - ', $hours);

What’s the best way to do this in Laravel/MySQL/PHP?



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-replace-unicode-characters-in-database/
via Lzo Media

How to use mock objects in php testing - development

How to use mock objects in php testing

I’m trying to learn how to test properly and am struggling to get my head around mocks in the scenario below. I don’t seem to be able to mock a class.

The main class uses a number of component classes to build a particular activity. I can test the component on it’s own and mock it correctly but when I try to integrate test within the main class it calls the real service not the mock service.

This is in a Laravel 5.5 app.

I have a base class:

class booking {

private $calEventCreator

    public function __construct(CalenderEventCreator $calEventCreator) {
       $this->calEventCreator = $calEventCreator;
    }
}

This is then extended by another class:

class EventType extends booking {

    //do stuff
}

The CalenderEventCreator relies on an external service which I want to mock.

class CalendarEventCreator {

    public function  __construct(ExternalService $externalService) {

        $this->externalService = $externalService;

    }
}

In my test I have tried to do the following:

public function test_complete_golf_booking_is_created_no_ticket()
{

    $this->booking = App::make(AppBookingEventType::class);

    $calendarMock = Mockery::mock(ExternalService::class);

    $calendarMock->shouldReceive([
        'create' => 'return value 1',
    ])->once();

    $this->booking->handle($this->attributes, 'booking');

}

But in trying to execute the test it’s clear the ExyernalService is not using the mocked object.

I have tried re-arranging the code as follows:

$calendarMock = Mockery::mock(Event::class);
    $calendarMock->shouldReceive([
        'create' => 'return value 1',
    ])->once();

    $this->booking = App::make(AppBookingEventType::class);

    $this->booking->handle($this->attributes, 'booking');
}

and tried:

$this->booking = App::make(AppBookingEventType::class, ['eventService'=>$calendarMock]);

But on each occassion the real service is called not the mock version

I’m learning this so apologies about fundamental errors but can someone explain how I should mock the external service correctly



from Laravel Questions and Answers https://laravelquestions.com/php/how-to-use-mock-objects-in-php-testing/
via Lzo Media

Laravel – how to send some value of a parameter from a blade view files to a controller? - development

Laravel – how to send some value of a parameter from a blade view files to a controller?

How to send value “” to some method in a controller?

e.g. show.blade.php – contains the value:

""

MyController.php – contains the method:

public function results(Request $request){
    //and here I want to use the value  
}



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-how-to-send-some-value-of-a-parameter-from-a-blade-view-files-to-a-controller/
via Lzo Media

i can’t access my laravel development server using IP address - development

i can’t access my laravel development server using IP address

i’m trying to build an android app that requires interaction with a database server , i’m using my own computer for this purpose , i’m running wampserver 3.1.0 . i installed laravel successfully using composer , however when i type 192.168.1.6:8000/ to test i get a webpage displaying this error :

The following error was encountered while trying to retrieve the URL: http://192.168.1.6:8000/

Connection to 192.168.1.6 failed.

The system returned: (110) Operation timed out

The remote host or network may be down. Please try the request again.

Your cache administrator is webmaster.

note that i already started the server using the “php artisan serve –host ipaddress” command , and the permissions in httpd.conf and httpd-vhosts.conf are configured correctly .what confuses me is that when i type the same url in my phone browser it shows the laravel page with no errors whatsoever !!! , help would be much appreciated .



from Laravel Questions and Answers https://laravelquestions.com/php/i-cant-access-my-laravel-development-server-using-ip-address/
via Lzo Media

Laravel call contoller from blade without route - development

Laravel call contoller from blade without route

I am developing cms and i want to make snippets like WordPress for ex: in the post content when someone type this post@getBySlug>hello-word This triger function getBySlug in post contoller.

Any idea please



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-call-contoller-from-blade-without-route/
via Lzo Media

Laravel two references to same table - development

Laravel two references to same table

I have a transactions tables with sender_id and receiver_id columns which are both references of user.

now, I want to create a hasMany relationship for the user.
(all user’s transaction, be it,received or sent)



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-two-references-to-same-table/
via Lzo Media

Wednesday, March 21, 2018

Laravel – Redirect even if no product selected - development

Laravel – Redirect even if no product selected

I have a system where a user can select an item, submit a request and move on. I need to give the user the option to NOT select an item and still be able to move on. In my current situation, I don’t know how to achieve that.

In my view, I display all the selectable items like this, using a foreach:

@foreach($themes as $theme)
<div class="col-md-4 mb-4">
<div class="card theme-card card-hover depth-2 border-0" id="theme-id-">
<a href="" class="theme-link" data-toggle="modal" data-target="#theme">
  <div class="card-header p-0">
    @if($theme->thumbnail != 0)
    <img src="https://s.tmimgcdn.com/scr/67400/magento-thema-over-boxen_67400-original.jpg?width=502&height=502" width="502" height="350" class="theme-card-img" alt=""> @else
    <img src="http://jis.gov.jm/media/blank.png" class="theme-card-img" alt=""> @endif
  </div>
  <div class="card-body">
    <div class="row">
      <div class="col-md-2 vertical-center">
        <i class="fab fa-magento fa-lg"></i>
      </div>
      <div class="col-md-10">
        <p class="m-0">{!! str_limit($theme->name, $limit = 32, $end = '...') !!}</p>
        <small></small>
      </div>
    </div>
  </div>
</a>
<div class="card-footer bg-white border-0 text-right pt-0">
  <div class="row">
    <div class="col-md-6 text-left">
      <input type="hidden" class="theme-name" name="theme[]"> 
      <button data-card-id="" class="btn btn-orange btn-sm btn-theme-choice">Kiezen</button>
    </div>
    <div class="col-md-6 text-right">
      <small class="text-muted" style="text-decoration: line-through">145 €</small><span style="font-size: 20px;">  €</span>
    </div>
  </div>
</div>
</div>
</div>
@endforeach

Here, I supply the ID of each product. Then in my jQuery file, I do the following: When a user presses the button. The ID gets called and the value of the input is being set to ‘selected’.

$('.btn-theme-choice').on('click', function (event) {
    event.preventDefault();
    newSelectedCardId = $(event.target).data('card-id');


    // console.log(newSelectedCardPkg);
    if(cardId === null) {
        cardId = newSelectedCardId;
    } else if (cardId !== newSelectedCardId) {
        $('#theme-id-' + cardId).removeClass('theme-chosen').find("input[name='theme["+cardId+"]']").val('');
        cardId = $(event.target).data('card-id');
    }


    var card = $('#theme-id-' + cardId );
    card.toggleClass('theme-chosen');
    selectedCardInput = card.find("input[name='theme["+cardId+"]']");
    selectedCardInput.val('selected');

    console.log(selectedCardInput);

});

So when a user clicks on one of the buttons. That product is getting ‘selected’. Now in my controller, I foreach all the inputs and check if the value is ‘selected’. If it is, a variable called $selectedTheme will be filled with the ID. Then I find the selected product and put its values in a session and then the user gets redirected to ‘/plugins’.

The problem is

When I don’t select a theme and submit the form. It gives me the error Trying to get property 'id' of none object. The user needs to be able to go to that link even if he/she did not select a product. If the user did not select a product. The session shouldn’t even be made. I know how to check if no product is selected in the if-statement that is inside the foreach loop but that’s about it. How can I achieve this?



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-redirect-even-if-no-product-selected/
via Lzo Media

Laravel – Queues reporting as failed (even though they don’t) - development

Laravel – Queues reporting as failed (even though they don’t)

I am using the latest version of Homestead.
I also have Laravel Horizon set up.
I am using redis as the queue driver.

What’s happening is my jobs are all failing (even though the job exits correctly).

I am running the job through command line by using a custom command:

vagrant@homestead:~/myapp$ artisan crawl:start
vagrant@homestead:~/myapp$ <-- No CLI errors after running

app/Console/Command/crawl.php

<?php

namespace MyAppConsoleCommands;

use IlluminateConsoleCommand;
use MyAppJobsCrawl;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Start long running job.';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {


        Crawl::dispatch();

    }

}

app/Jobs/Crawl.php

<?php

namespace MyAppJobs;

use IlluminateBusQueueable;
use IlluminateQueueSerializesModels;
use IlluminateQueueInteractsWithQueue;
use IlluminateContractsQueueShouldQueue;
use IlluminateFoundationBusDispatchable;

class Crawl implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * The number of seconds the job can run before timing out.
     *
     * @var int
     */
    public $timeout = 3600;

    /**
     * The number of times the job may be attempted.
     *
     * @var int
     */
    public $tries = 1;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {

    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {


        $crawl = new Crawl();
        $crawl->start();


    }
}

app/Crawl.php

<?php
namespace MyApp;

class Crawl
{

    public function start()
    {

        ini_set('memory_limit','256M');
        set_time_limit(3600);

        echo "Started."; 
        sleep(30);
        echo "Exited.";
        exit(); 

    }
}

worker.log

[2018-03-21 10:14:27][1] Processing: MyAppJobsCrawl
Started.
Exited.
[2018-03-21 10:15:59][1] Processing: MyAppJobsCrawl
[2018-03-21 10:15:59][1] Failed:     MyAppJobsCrawl

From Horizon’s failed job detail

Failed At    18-03-21 10:15:59
Error        IlluminateQueueMaxAttemptsExceededException:
             MyAppJobsCrawl has been attempted too many 
             times or run too long. The job may have previously 
             timed out. in /home/vagrant/app/vendor/laravel
             /framework/src/Illuminate/Queue/Worker.php:396

laravel-worker.conf

[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /home/vagrant/myapp/artisan queue:work --sleep=3 --tries=1 --timeout=3600
autostart=true
autorestart=true
user=vagrant
numprocs=1
redirect_stderr=true
stdout_logfile=/home/vagrant/myapp/worker.log

Synopsis

Looking at my worker.log I can see that the output from my class has worked:

Started.
Exited.

But the job is reported as failed. Why?

Any help is greatly appreciated!



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-queues-reporting-as-failed-even-though-they-dont/
via Lzo Media

Why am l getting "access not configured" error why trying to make an api call to google analytics reporting? - development

Why am l getting "access not configured" error why trying to make an api call to google analytics reporting?

l am trying to integrate google analytics reporting to a laravel website hosted locally and its giving me this error

{"error":{"errors":[{"domain":"usageLimits","reason":"accessNotConfigured","message":"Access Not Configured. Google Analytics API has not been used in project 463423597673 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/analytics.googleapis.com/overview?project=463423597673 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.","extendedHelp":"https://console.developers.google.com/apis/api/analytics.googleapis.com/overview?project=463423597673"}],"code":403,"message":"Access Not Configured. Google Analytics API has not been used in project 463423597673 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/analytics.googleapis.com/overview?project=463423597673 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry."}} ◀"

l have enabled the api in the dashboard and can not seem to solve it.Below is the controller class

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppModelsOrder;
use AppModelsUser;
use Analytics;
use SpatieAnalyticsPeriod;

class AdminDashboardController extends Controller
{
    //
  public function __construct(){

    $this->middleware('auth');

  }

    public function create(){

      $analyticsData = Analytics::fetchVisitorsAndPageViews(Period::days(7));

      $orders = Order::limit(5)->get();
      $users = User::limit(5)->get();

        return view('admin.admin-dashboard',compact('orders','users'));
    }




    public function destroy(){

        auth()->logout();

        return redirect('/admin');
    }


}

Please any assistance is appreciated



from Laravel Questions and Answers https://laravelquestions.com/php/why-am-l-getting-access-not-configured-error-why-trying-to-make-an-api-call-to-google-analytics-reporting/
via Lzo Media

Arrange the array by pid - development

Arrange the array by pid

I have an array selected from database like this

$authList = [
    ['id' => 1, 'pid' => 0, 'title' => 'project'],
    ['id' => 2, 'pid' => 1, 'title' => 'customer'],
    ['id' => 3, 'pid' => 2, 'title' => 'select'],
];

And I want to arrange the array by “pid” like this

$result = [
    [
        'id' => 1,
        'pid' => 0,
        'title' => 'project',
        'children' => [
            [
                'id' => 2,
                'pid' => 1,
                'title' => 'select',
                'children' => [
                    'id' => 3,
                    'pid' => 2,
                    'title' => 'select'
                ]
            ],
        ]
    ],
];

So could anyone provide me an efficient function to arrive the goal. Any
response or suggestion would appreciated



from Laravel Questions and Answers https://laravelquestions.com/php/arrange-the-array-by-pid/
via Lzo Media

Laravel: to make external modules independent - development

Laravel: to make external modules independent

We developed a modular project in Laravel 5.1. There are lots of core modules and models that use these modules. In our case, if the inserted module uses other modules, it will be related to those models dynamically.
When I remove the module from project by hand, I need to remove its dependencies from each module. We want establish relations without creating dependency between modules.

For example;

User model from account module used by other many other modules. Assume we have discussion module.
When we build a relationship for discussion model, we can reach the user of the corresponding model. However, if we establish a relationship with the user model, this project will no longer be a moduler.
We want to add dynamic functions to the user module from discussion module.

Temporarily, we add this code fragment to user module.

/**
     * @return mixed
     */
    public function lastAnswer() {
        if( class_exists( Config::get( 'account.models.discussion' ) ) ) {
            return $this->hasOne( Config::get( 'account.models.answer' ) )->latest();
        }

        return null;
    }

If the config file has a relation, we link it, otherwise it will not be linked or we will return null.

But we want to add this dinamically from discussion module rather than account module.

If we accomplish this, whenever we add or remove the discussion module from project, it will continue to run without problem.

We tried to add laravel macroable as a trait but we could’t make it work in model files. It gives scope error.

For transformers files we are able to do this but in model files it didn’t work.



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-to-make-external-modules-independent/
via Lzo Media

http error: 400 | {"msg":"Message must be no more than 64k"} while trying to use Iron to send queued emails - development

http error: 400 | {"msg":"Message must be no more than 64k"} while trying to use Iron to send queued emails

I am trying to use Iron in Laravel 5.0 project and we are using Mail::queue() to send our emails but we are getting

http error: 400 | {"msg":"Message must be no more than 64k"} 

this mail works if we directly send it but we are getting this when we are using Mail::queue()

Error stack trace

in IronCore.class.php line 358
at IronCore->reportHttpError('400', '{"msg":"Message must be no more than 64k"}') in IronCore.class.php line 349

Any advise on this will be highly appreciated.



from Laravel Questions and Answers https://laravelquestions.com/php/http-error-400-msgmessage-must-be-no-more-than-64k-while-trying-to-use-iron-to-send-queued-emails/
via Lzo Media

Laravel – Scheduling a Large Task - development

Laravel – Scheduling a Large Task

Trying to run a function in Laravel that’s quite large and fetches a lot of data from Google Places API and stores parts in my database as new entries in a table. The problem is it auto-discovers new entries for me near my current entries, and that creates more jobs.

When I just access the command via GET it times out eventually. I’ve tried running it as a scheduled command with Redis but to be frank I can’t seem to figure out how it works. I’ve created a job, I tried to queue it with dispatch, but then it tries to run it immediately right now and it times out eventually again.

How do I run this large task without it pausing my entire server?

Thanks

  • Zach


from Laravel Questions and Answers https://laravelquestions.com/php/laravel-scheduling-a-large-task/
via Lzo Media

Doctrine lifecycle callbacks don’t fire - development

Doctrine lifecycle callbacks don’t fire

I want to create an identifier for my invoices, after I persist them. I’m using an auto generated ID in my identifier, so I have to use some postPersist callback to achieve this. However, my postPersist callback doesn’t get fired.

Here is my AbstractInvoice entity:

<?php

namespace AppInvoice;

use DoctrineORMMapping as ORM;

/**
 * @ORMEntity
 * @ORMHasLifecycleCallbacks
 * @ORMTable("invoices")
 * @ORMInheritanceType("SINGLE_TABLE")
 * @ORMDiscriminatorColumn(name="type", type="integer")
 * @ORMDiscriminatorMap({
 *     "0"="Regular",
 *     "1"="Credit"
 * })
 */
abstract class AbstractInvoice
{
    /**
     * @ORMId()
     * @ORMColumn(type="integer")
     * @ORMGeneratedValue(strategy="AUTO")
     * @var int
     */
    protected $id;

    /**
     * @ORMColumn(type="string")
     * @var string
     */
    protected $identifier;

    /**
     * @ORMPostPersist
     */
    protected function onPersist(): void
    {
        $this->identifier = '1' . str_pad($this->id, 5, '0', STR_PAD_LEFT);
    }
}

And here is my Regular invoice entity:

<?php

namespace AppInvoice;

use DoctrineORMMapping as ORM;

/**
 * @ORMEntity
 */
class Regular extends AbstractInvoice
{
}

I create an instance of the regular invoice entity in my controller:

<?php

namespace App;

use AppInvoiceRegular;

class Controller
{
    public function handle(InvoiceRepository $invoices)
    {
        $invoice = new Regular();
        $invoices->add($invoice);
    }
}

Which uses this repository:

<?php

namespace App;

use AppInvoiceAbstractInvoice;
use DoctrineORMEntityRepository;

class InvoiceRepository extends EntityRepository
{
    public function add(AbstractInvoice $invoice): void
    {
        $this->_em->persist($invoice);
        $this->flush();
    }
}

The invoice gets stored fine, only the onPersist method doesn’t get fired. I already tried implementing the callback in the sub class (Regular), switching to a public method. No success there. Am I missing something?

Thank you!



from Laravel Questions and Answers https://laravelquestions.com/php/doctrine-lifecycle-callbacks-dont-fire/
via Lzo Media

Creating a Service Provider in Laravel for a Vendor Package - development

Creating a Service Provider in Laravel for a Vendor Package

I’ve installed the following package into laravel:

https://github.com/omnilance/graphql-php-client

I want to bind the GraphQL class in the service provider with some config values and access it like:

app(OmnilanceGraphQLClient::class)->response()

Below is what I have so far. How would I set the host and other options the class provides? Do I do it in the boot method?

<?php

namespace AppProviders;

use OmnilanceGraphQLClient as GraphQL;
use IlluminateSupportServiceProvider;

class GraphQLServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
     //   $client->setHost($app['config']->get('graphql.host'));
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(OmnilanceGraphQLClient::class, function($app) {
            return new GraphQL(
                $app['config']->get('graphql.token')
            );
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [OmnilanceGraphQLClient::class];
    }
}



from Laravel Questions and Answers https://laravelquestions.com/laravel/creating-a-service-provider-in-laravel-for-a-vendor-package/
via Lzo Media

How to logout automatically from all tabs when I logout from anyone tab in laravel? - development

How to logout automatically from all tabs when I logout from anyone tab in laravel?

I am building a project in laravel. The testing team has suggested me to keep a check that if the user is logged in and has opened many tabs. At once, he logout from any one of the tabs, the applications must automatically logout him from all the tabs. This functionality in present in facebook.



from Laravel Questions and Answers https://laravelquestions.com/php/how-to-logout-automatically-from-all-tabs-when-i-logout-from-anyone-tab-in-laravel/
via Lzo Media

Tuesday, March 20, 2018

How to use GUZZLE Package in laravel to send xml request? - development

How to use GUZZLE Package in laravel to send xml request?

Have any one used GUZZLE Package in laravel 5.6 to send xml request into given wsdl link and get response and manipulated it..



from Laravel Questions and Answers https://laravelquestions.com/laravel/how-to-use-guzzle-package-in-laravel-to-send-xml-request/
via Lzo Media

Can’t find Backpack/Crudnews files - development

Can’t find Backpack/Crudnews files

I have a fresh install of laravel (using composer) and Backpack (using composer) and on top of that i installed Crudnews (also using composer) and everything works fine.

But i want to add an “author” column to the Crudnews form so when i started looking for the files (following the documentation) i realise that the only files i have are the migration files. I changed those and migrated and now i have the extra “author” field in my database, so that works. But i can’t find the controllers or route files ANYWHERE.

I have looked through all my folders and there are no files that has to do with Crudnews and i’m so confused. They should be there since it works, but i can’t find them. But if they arent there the app should break.

Has anyone had similar problems? Or maybe anyone has a solution?


PHP: 7.1.14
Valet (Server environment): 2.0.7
System: Mac OS, 10.13.3

from Laravel Questions and Answers https://laravelquestions.com/php/cant-find-backpack-crudnews-files/
via Lzo Media

how to view selected dates back on the same page after executing function - development

how to view selected dates back on the same page after executing function

so i have a form like so:

<form role="form" action="" autocomplete="off" method="POST">
  
  <div class="form-group-attached">
    <div class="row">
      <div class="col-lg-6">
        <div class="form-group form-group-default required" >
          <label>From</label>
          <input type="date" class="form-control" name="from" required>
        </div>
      </div>
      <div class="col-lg-6">
        <div class="form-group form-group-default required" >
          <label>To</label>
          <input type="date" class="form-control" name="to" required>
        </div>
      </div>
    </div>
  </div>
  <br/>
  <button class="btn alt-btn-black btn-sm alt-btn pull-right" type="submit">Filter Date</button>
</form>

and there is a graph on that same page. so at first the graph displays data for all the dates.. so i set the form for user to select from and to dates so they can filter the chart to the dates selected.. so in my controller;

public function viewgraphByDate(Request $request, $companyID)
{
$companyID = $this->decode($companyID);

$match = count(DiraChatLog::where('company_id', $companyID)->where('date_access', '>=', $request->from)->where('date_access', '<=', $request->to)->where('status', 'Match')->get());
$noAnswer = count(DiraChatLog::where('company_id', $companyID)->where('date_access', '>=', $request->from)->where('date_access', '<=', $request->to)->where('status', 'No Answer')->get());
$missing = count(DiraChatLog::where('company_id', $companyID)->where('date_access', '>=', $request->from)->where('date_access', '<=', $request->to)->where('status', 'Missing')->get());
// dd($match,$noAnswer,$missing);

$email = count(DiraResponses::where('company_id', $companyID)->where('created_at', '>=', $request->from)->where('created_at', '<=', $request->to)->where('type', 'email')->where('format', 'email')->get());
$pdf = count(DiraResponses::where('company_id', $companyID)->where('created_at', '>=', $request->from)->where('created_at', '<=', $request->to)->where('type', 'media')->where('format', 'pdf')->get());
$image = count(DiraResponses::where('company_id', $companyID)->where('created_at', '>=', $request->from)->where('created_at', '<=', $request->to)->where('type', 'media')->where('format', 'image')->get());
$video = count(DiraResponses::where('company_id', $companyID)->where('created_at', '>=', $request->from)->where('created_at', '<=', $request->to)->where('type', 'media')->where('format', 'video')->get());
// dd($email,$pdf,$image,$video);

$text = count(DiraResponses::where('company_id', $companyID)->where('type', 'text')->where('format', 'text')->get());
$totalMedia = $email + $pdf + $image + $video;
// dd($text,$totalMedia);

$from = $request->from;
$to = $request->to;
// dd($from, $to);

$companyID = $this->encodeID($companyID);

return view('AltHr.Chatbot.viewgraph', compact('companyID','match','noAnswer','missing','email','pdf','image','video','text','totalMedia','from','to'));
}

as you can see this function returns to the same page with the graph showing the dates selected by user.. now i want to know how can i display to user the dates the selected? either in the input date box or out is fine..?



from Laravel Questions and Answers https://laravelquestions.com/php/how-to-view-selected-dates-back-on-the-same-page-after-executing-function/
via Lzo Media