mercredi 28 février 2018

excessive delay in queue - laravel

Goodnight I need to send more than 1000 emails for each event created, and for this I use queue (as Laravel's documentation says), but when sending the emails I have to wait until all the emails are sent to return to the view of control Panel

this is my "store" function in NewsEvents.php controller that sends the emails

 public function store(Request $request)
{
    $attributes = request()->validate(News::$rules, News::$messages);

    $news = $this->createEntry(News::class, $attributes);

    //queue for sending emails 
     $this->dispatch(new Nevent($news));


    return redirect_to_resource();
}

the "handle" function of job "Nevent.php"

 public function handle()
{
    //   
     $users=User::where('tipo_user','user')->get();                  
         foreach($users as $user)
         {
             $user->notify(new EventCreated($this->news));
             echo 'enviado correo';
             Informe::create([
                'event_id' => $this->news->id,
                'total' => '1',
                'tipo' => 'invitacion',
                'dst_id' => $user->id,
                'estado' => 'correcto',
            ]);

         }
}

What could be the problem?



via Chebli Mohamed

Laravel - When using 3rd party packages and when not

I wonder, when should be better to use 3rd party packages and when not, when should be better to not reinvent the wheel with custom code, and when not.

Exist some general rules about this? what is the maximum number of external packages to avoid?

What are the common checks for choose packages that have same functionalities?..other than check if is lightweight, better supported and who is the developer.

Is a good idea to use packages also for simple stuff?



via Chebli Mohamed

What todo when composer update and composer install give error ?

I run composer install I got this error, telling me to use composer update

Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Warning: The lock file is not up to date with the latest changes in composer.json. You may be getting outdated dependencies. Run update to update them.
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for doctrine/inflector v1.3.0 -> satisfiable by doctrine/inflector[v1.3.0].
    - doctrine/inflector v1.3.0 requires php ^7.1 -> your PHP version (7.0.25) does not satisfy that requirement.
  Problem 2
    - Installation request for symfony/css-selector v4.0.3 -> satisfiable by symfony/css-selector[v4.0.3].
    - symfony/css-selector v4.0.3 requires php ^7.1.3 -> your PHP version (7.0.25) does not satisfy that requirement.
  Problem 3
    - Installation request for symfony/event-dispatcher v4.0.3 -> satisfiable by symfony/event-dispatcher[v4.0.3].
    - symfony/event-dispatcher v4.0.3 requires php ^7.1.3 -> your PHP version (7.0.25) does not satisfy that requirement.
  Problem 4
    - Installation request for doctrine/instantiator 1.1.0 -> satisfiable by doctrine/instantiator[1.1.0].
    - doctrine/instantiator 1.1.0 requires php ^7.1 -> your PHP version (7.0.25) does not satisfy that requirement.
  Problem 5
    - doctrine/inflector v1.3.0 requires php ^7.1 -> your PHP version (7.0.25) does not satisfy that requirement.
    - laravel/framework v5.5.32 requires doctrine/inflector ~1.1 -> satisfiable by doctrine/inflector[v1.3.0].
    - Installation request for laravel/framework v5.5.32 -> satisfiable by laravel/framework[v5.5.32].

I run composer update, I got this

Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - doctrine/dbal v2.6.3 requires php ^7.1 -> your PHP version (7.0.25) does not satisfy that requirement.
    - doctrine/dbal v2.6.2 requires php ^7.1 -> your PHP version (7.0.25) does not satisfy that requirement.
    - doctrine/dbal v2.6.1 requires php ^7.1 -> your PHP version (7.0.25) does not satisfy that requirement.
    - doctrine/dbal v2.6.0 requires php ^7.1 -> your PHP version (7.0.25) does not satisfy that requirement.
    - Installation request for doctrine/dbal ^2.6 -> satisfiable by doctrine/dbal[v2.6.0, v2.6.1, v2.6.2, v2.6.3].

Now what should I do ?

This is what I have in composer.json

cat composer.json

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=7.0.0",
        "anouar/paypalpayment": ">=3.0",
        "doctrine/dbal": "^2.6",
        "fideloper/proxy": "~3.3",
        "guzzlehttp/guzzle": "^6.3",
        "intervention/image": "^2.4",
        "laravel/framework": "5.5.*",
        "laravel/tinker": "~1.0",
        "spatie/laravel-newsletter": "^4.1",
        "srmklive/paypal": "~1.0"
    },
    "require-dev": {
        "filp/whoops": "~2.0",
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "~1.0",
        "phpunit/phpunit": "~6.0"
    },
    "autoload": {
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "psr-4": {
            "App\\": "app/"
        },
        "files": ["app/Http/Helper.php"]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "extra": {
        "laravel": {
            "dont-discover": [
            ]
        }
    },
    "scripts": {
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate"
        ],
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover"
        ]
    },
    "config": {
        "preferred-install": "dist",
        "sort-packages": true,
        "optimize-autoloader": true
    }
} 



via Chebli Mohamed

Select items by data from pivot table

I have a summary table created in this way:

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('article_tag', function (Blueprint $table) {
        $table->integer('article_id')->unsigned();
        $table->foreign('article_id')->references('id')->on('articles');
        $table->integer('tag_id')->unsigned();
        $table->foreign('tag_id')->references('id')->on('tags');

    });
}

Result:

article_id tag_id
1            3
1            4
2            4

How select article_id by tag_id?

My attempts: $article = Article::select(['id', 'title', 'text', 'image_file'])->where('tags', $request);



via Chebli Mohamed

laravel, basic instalation, redirect give me back a 500 Error

I have make a basic instalation of Laravel 5.6.5 with composer, and also I have added socialite plugin.

I have read some stackoverflow question, but I dont't get it works.

If I run laravel with php artisan serve it works, but If I try to use the local Apache (2.4.18) It give me back this error:

[Wed Feb 28 19:19:21.079971 2018] [authz_core:debug] [pid 6892] mod_authz_core.c(809): [client 127.0.0.1:35198] AH01626: authorization result of Require all granted: granted
[Wed Feb 28 19:19:21.080019 2018] [authz_core:debug] [pid 6892] mod_authz_core.c(809): [client 127.0.0.1:35198] AH01626: authorization result of <RequireAny>: granted
[Wed Feb 28 19:19:21.080489 2018] [core:error] [pid 6892] [client 127.0.0.1:35198] AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.
[Wed Feb 28 19:19:21.080495 2018] [core:debug] [pid 6892] core.c(3628): [client 127.0.0.1:35198] AH00121: r->uri = /public/public/public/public/public/public/public/public/public/public/
[Wed Feb 28 19:19:21.080497 2018] [core:debug] [pid 6892] core.c(3635): [client 127.0.0.1:35198] AH00122: redirected from r->uri = /public/public/public/public/public/public/public/public/public/
[Wed Feb 28 19:19:21.080499 2018] [core:debug] [pid 6892] core.c(3635): [client 127.0.0.1:35198] AH00122: redirected from r->uri = /public/public/public/public/public/public/public/public/
[Wed Feb 28 19:19:21.080501 2018] [core:debug] [pid 6892] core.c(3635): [client 127.0.0.1:35198] AH00122: redirected from r->uri = /public/public/public/public/public/public/public/
[Wed Feb 28 19:19:21.080503 2018] [core:debug] [pid 6892] core.c(3635): [client 127.0.0.1:35198] AH00122: redirected from r->uri = /public/public/public/public/public/public/
[Wed Feb 28 19:19:21.080504 2018] [core:debug] [pid 6892] core.c(3635): [client 127.0.0.1:35198] AH00122: redirected from r->uri = /public/public/public/public/public/
[Wed Feb 28 19:19:21.080506 2018] [core:debug] [pid 6892] core.c(3635): [client 127.0.0.1:35198] AH00122: redirected from r->uri = /public/public/public/public/
[Wed Feb 28 19:19:21.080508 2018] [core:debug] [pid 6892] core.c(3635): [client 127.0.0.1:35198] AH00122: redirected from r->uri = /public/public/public/
[Wed Feb 28 19:19:21.080509 2018] [core:debug] [pid 6892] core.c(3635): [client 127.0.0.1:35198] AH00122: redirected from r->uri = /public/public/
[Wed Feb 28 19:19:21.080511 2018] [core:debug] [pid 6892] core.c(3635): [client 127.0.0.1:35198] AH00122: redirected from r->uri = /public/
[Wed Feb 28 19:19:21.080512 2018] [core:debug] [pid 6892] core.c(3635): [client 127.0.0.1:35198] AH00122: redirected from r->uri = /
[Wed Feb 28 19:19:21.134407 2018] [authz_core:debug] [pid 6894] mod_authz_core.c(809): [client 127.0.0.1:35200] AH01626: authorization result of Require all granted: granted, referer: http://laravel.local/
[Wed Feb 28 19:19:21.134426 2018] [authz_core:debug] [pid 6894] mod_authz_core.c(809): [client 127.0.0.1:35200] AH01626: authorization result of <RequireAny>: granted, referer: http://laravel.local/
[Wed Feb 28 19:19:21.134607 2018] [core:error] [pid 6894] [client 127.0.0.1:35200] AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace., referer: http://laravel.local/
[Wed Feb 28 19:19:21.134612 2018] [core:debug] [pid 6894] core.c(3628): [client 127.0.0.1:35200] AH00121: r->uri = /public/public/public/public/public/public/public/public/public/public/favicon.ico, referer: http://laravel.local/
[Wed Feb 28 19:19:21.134614 2018] [core:debug] [pid 6894] core.c(3635): [client 127.0.0.1:35200] AH00122: redirected from r->uri = /public/public/public/public/public/public/public/public/public/favicon.ico, referer: http://laravel.local/
[Wed Feb 28 19:19:21.134616 2018] [core:debug] [pid 6894] core.c(3635): [client 127.0.0.1:35200] AH00122: redirected from r->uri = /public/public/public/public/public/public/public/public/favicon.ico, referer: http://laravel.local/
[Wed Feb 28 19:19:21.134618 2018] [core:debug] [pid 6894] core.c(3635): [client 127.0.0.1:35200] AH00122: redirected from r->uri = /public/public/public/public/public/public/public/favicon.ico, referer: http://laravel.local/
[Wed Feb 28 19:19:21.134619 2018] [core:debug] [pid 6894] core.c(3635): [client 127.0.0.1:35200] AH00122: redirected from r->uri = /public/public/public/public/public/public/favicon.ico, referer: http://laravel.local/
[Wed Feb 28 19:19:21.134625 2018] [core:debug] [pid 6894] core.c(3635): [client 127.0.0.1:35200] AH00122: redirected from r->uri = /public/public/public/public/public/favicon.ico, referer: http://laravel.local/
[Wed Feb 28 19:19:21.134627 2018] [core:debug] [pid 6894] core.c(3635): [client 127.0.0.1:35200] AH00122: redirected from r->uri = /public/public/public/public/favicon.ico, referer: http://laravel.local/
[Wed Feb 28 19:19:21.134629 2018] [core:debug] [pid 6894] core.c(3635): [client 127.0.0.1:35200] AH00122: redirected from r->uri = /public/public/public/favicon.ico, referer: http://laravel.local/
[Wed Feb 28 19:19:21.134630 2018] [core:debug] [pid 6894] core.c(3635): [client 127.0.0.1:35200] AH00122: redirected from r->uri = /public/public/favicon.ico, referer: http://laravel.local/
[Wed Feb 28 19:19:21.134632 2018] [core:debug] [pid 6894] core.c(3635): [client 127.0.0.1:35200] AH00122: redirected from r->uri = /public/favicon.ico, referer: http://laravel.local/
[Wed Feb 28 19:19:21.134634 2018] [core:debug] [pid 6894] core.c(3635): [client 127.0.0.1:35200] AH00122: redirected from r->uri = /favicon.ico, referer: http://laravel.local/

This is my vhost:

<VirtualHost *:80>
    ServerName laravel.local

    ServerAdmin webmaster@localhost
    DocumentRoot /home/oskar/Webapps/Laravel/twitter_follow/public
        <Directory   /home/oskar/Webapps/Laravel/twitter_follow/public>
        AllowOverride All
                Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
                <Limit GET POST PUT DELETE OPTIONS>
                        Require all granted
                </Limit>

                <LimitExcept GET POST PUT DELETE OPTIONS>
                        Require all denied
                </LimitExcept>
        </Directory>
    ErrorLog ${APACHE_LOG_DIR}/laravel_local.error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel debug

    CustomLog ${APACHE_LOG_DIR}/laravel_local.access.log combined
</VirtualHost>

And this is the .htaccess file:

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

Any idea what's going on?

Thanks.

Oskar



via Chebli Mohamed

Laravel authentication & authorisation with REMOTE_USER

I've got the following setup:

Apache Server 2.4.x which uses Kerberos for SSO Laravel 5.5 PHP 7.x MSSQL Database 12 with existing database structure, Usertable can be customized

In my Laravel application a user can access the application only if he/she already passed the apache login which means i can retrieve the REMOTE_USER variable from the server with

$user = $_SERVER['REMOTE_USER'];

What i intend to do is to use the Laravel authentication and authorisation for the rest of the application. I've looked into a lot of examples but found nothing which really suits.

Can anybody give a hint how to authenticate the $user in Laravel when accessing the application to get the credentials?



via Chebli Mohamed

How to make csv import work on both mac and windows

I simply would like to import this text from a csv file into a laravel php script that parses it:

store_id,ref,priority,tagline
10,confuscian,5,confuscian says

when I send this on a mac machine on chrome, the body of the csv appears like this:

enter image description here

enter image description here

so you can see that a \n is added:

{"csv":"store_id,ref,priority,tagline\n10,confuscian,5,confuscian says"}

however, when I add the same csv from windows, it appears like so:

{"csv":"store_id,ref,priority,tagline 10,confuscian,5,confuscian says"}

the script that reads this filters out the \r\n different OS problem like so:

    $file = storage_path('batch_update.csv');
    // replace new line characters for mac/win/linux
    $str = preg_replace('/(\r\n|\r|\n)+/', "\n", $this->data);
    file_put_contents($file, $str); 

    $this->data = $this->csvToArray($file);

    if (!$this->data || !$this->checkForRequiredColumns()) {
        return false;
    }

the problem is that in windows, the \n doesn't even show up! which confuses the csvToArray script:

trait CsvHelpers { private function csvToArray($filename) { if (!file_exists($filename) || !is_readable($filename)) { return false; }

    $header = null;
    $data   = array();
    if (($handle = fopen($filename, 'r')) !== false) {
        while (($row = fgetcsv($handle, 1000, ',')) !== false) {
            $row = array_map('trim', $row);
            if (!$header) {
                $header = $row;
            } else {
                $data[] = array_combine($header, $row);
            }
        }
        fclose($handle);
    }
    return $data;
}

question

how do i make it so that when i export a csv in windows, every line ends in \n?



via Chebli Mohamed

Use of @push and @stack for complex Laravel Blade layout

Working with Blade (Laravel template engine), I have two layouts:

  1. guest.blade.php, for guest related stuff (login, password request, etc.). Basically it's a slim template where content is centered (mostly forms)
  2. auth.blade.php, for authenticated users stuff (you know, the full layout with header, sidebar, etc.)

These two layouts have the following features:

  1. They share some common CSS and JS (bootstrap, font-awesome, jquery, etc.) in two different partials (css.blade.php in the document head and js.blade.php at the bottom).
  2. The auth.blade.php has obviously additional assets that aren't useful in slimmer guest.blade.php but are required in (mostly) ALL of the auth pages (select2, jquery-ui, etc.). Yes, I could put these CSS' and JS' in previously mentioned css.blade.php and js.blade.php and have them all in one file, but they would bloat guest.blade.php that I'd like to keep slim. And of course I don't want to put them in every child view! :-)
  3. Some views (both auth and guest related) could ask for peculiar assets just for that view: a dashboard could require some charts assets, a media manager could require multi-uploader assets, a login page could require a CSS or JS just for that login view.
  4. Last but not least, the order in which assets are loaded is important: i.e. for CSS
    • bootstrap, font-awesome, etc.
    • additional_css_only_for_auth_template
    • peculiar_css_plugin_for_the_current_view*
    • css_layout_(adminlte)
    • peculiar_css_custom_styles_for_the_current_view**
    • custom_global_styles_to_override_adminlte

Summing, the goal is to keep one single css.blade.php for both guest.blade.php and auth.blade.php (1), add the shared auth assets when using the auth template (2), and being able to set custom assets per-view, equally when using guest and auth template (3) - and the same goes for javascript assets

* css plugins are mostly retrieved from cdn
** these are additional styles only for that view


Oh, really I think I did, but don't know if it's the right approach since it seems a strange use of @push and @stack and I'd like to know if there's a cleaner solution

layouts.guest.blade.php

...
@include('partials.css')
...

layouts.auth.blade.php

@include('partials.stack') 
...
@include('partials.css')
...

partials.css.blade.php

<!-- shared css, in auth and guest layout -->
<link href="bootstrap.css">
<link href="font-awesome.css">

<!-- shared css plugins, but only for auth layout -->
@stack('shared-auth')

<!-- peculiar css plugins for this page only -->
@stack('css-plugins')

<!-- now this is the shared layout, for auth and guest -->
<link href="adminlte.css">

<!-- pecualiar css styles, for this page only -->
@stack('css-styles')

<!-- theme, for the auth layout only -->
@stack('theme')

<!-- my global custom css -->
<link href="style.css"> 

partials.stack.blade.php (remember, this goes only on top of auth layout, so it contains the auth shared assets)

@push('shared-auth')
    <link href="jquery-ui">
    <link href="select2">
@endpush

@push('theme')
    <link href="skin-blue">
@endpush

dashboard.blade.php

@push('css-plugins')
    <link href="chart.css">
@endpush

@push('css-styles')
    <link ="custom_chart_modifications.css">
@endpush

login.blade.php

@push('css-plugins')
    <link href="icheck-blue.css">
@endpush

@push('css-styles')
    <link href="custom_style_for_login_only.css">
@endpush


Does it makes sense? The weird part to me is the @include('partials.stack') on top of layouts.auth.blade.php that pushes to the @stack of the other included file @include('partials.css')

It seems to me an uncommon (and undocumented, as far as I googled...) use of @push and @stack: are there better and recommended alternatives?



via Chebli Mohamed

how to retrieve multiple records from many to many relationship in laravel

thanks in advance, i have a problem with retrieving data from many to many relationship, i have orders and every order has many products, and i'm making an analysis aboat how many products sold in today's orders but when i'm calling more than 1 order id an error appears says that the relationship method dosen't exist.
orders model:

 class orders extends Model {
  protected $table = 'orders';
  public $timestamps = false;
  protected $fillable = [
    'serial', 'clientName', 'phone', 'cost', 'notes', 'received_by', 'received_at'
  ];
  public function product() {
    return $this->belongsToMany('\App\Products', 'order_product', 'order_id', 'product_id')->withPivot('product_id', 'count');
  }
}

products model:

class Products extends Model {
  protected $table = 'products';
  public $timestamps = false;
  protected $fillable = [
    'name', 'cost', 'available', 'notes', 'created_at'
  ];
  public function order() {
    return $this->belongsToMany('\App\Orders', 'order_product', 'product_id', 'order_id')->withPivot('order_id', 'product_id', 'count');
  }
}


and here is the controller

$today_orders = Orders::where('received_at', '>=', Carbon::today()->startOfDay())->where('received_at', '<=', Carbon::today()->endOfDay());
$today_orders_ids = array();
foreach($today_orders->get() as $order) {
   array_push($today_orders_ids, $order->id);
}
$today_orders_products = Orders::find($today_orders_ids)->product()->get();

the error message:

BadMethodCallException
Method product does not exist.

is there is an error in my code ? or i can't get multiple records from a relationship
note:

everything works perfectly until the find() method, both the relationship and retrieving today orders



via Chebli Mohamed

How to make leftjoin in laravel 5.4

I have two table 1)clients 2)orders. I trying to make leftjoin but I not getting correct result what i want. Please see image below.

Thanks

ClientController.php

$clients = Client::leftjoin('orders','orders.client_id','=','clients.id')
                    ->select(DB::raw("count(orders.id) as orderCount"),
                    'clients.name as name','clients.email as email',
                    'clients.phone as phone','clients.country as country',
                    'orders.total_amount')
                    ->where('orders.status',0)
                    ->get();

enter image description here



via Chebli Mohamed

custom translate on values in laravel validation

I have a conditional validation on laravel 5.6:

 'body' => 'required_if:body.*.type,left',

in validation.php

"required_if"      => " :attribute is required when :other is :value",

and it a messsage like this:

text is required when type is left",

I want translate "left" word to my custom word.

Is it possible to di that?

I try these:

'attributes' => array(
   'left' => 'left2'
),

or

'value' => array(
   'left' => 'left2'
),

but no success!



via Chebli Mohamed

Test methods fail using Storage. Illuminate\Http\Testing\imagepng() in Laravel

Hello, I'm doing TDD to test my development, my tests were passing until I decided to reinstall php to repair the sqlite driver for testing (the main driver is mysql). So when I run my hole suite of tests this error shows in every method that uses the storage:

Error : Call to undefined function Illuminate\Http\Testing\imagepng()
 {laravel}/framework/src/Illuminate/Http/Testing/FileFactory.php:46
 {laravel}/framework/src/Illuminate/Support/helpers.php:1038
 {laravel}/framework/src/Illuminate/Http/Testing/FileFactory.php:49
 {laravel}/framework/src/Illuminate/Http/Testing/FileFactory.php:31
 {laravel}/tests/Feature/FacilityTest.php:38

This one is a method that throws the above error (the line 38 is signaled):

/**
 * @test
 * Test for: a Facility can be registered by an admin.
 */
public function a_facility_can_be_registered_by_an_admin()
{
    /** Given a correct information for a facility */
    \Storage::fake('public');

   // Next line is 38 the problematic one:
    $data = ["name" => "Facility A", 'image' => UploadedFile::fake()->image('facility-a.jpg')];

    /** When the request is made by an admin */
    $admin = $this->createUser([], 'admin');
    $response = $this->apiAs($admin, 'POST', '/api/v1/manage/facilities', $data);

    /** Then the facility should be registered */
    $response->assertStatus(Response::HTTP_CREATED);
}

I really don't know why.


If this helps, this is my phpunit file:

phpunit.xml

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>

        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
        <env name="DB_CONNECTION" value="sqlite"/>
    </php>
</phpunit>


Thanks in advance.



via Chebli Mohamed

How to mock user creation if password is hidden in Laravel 5.5 unit tests

I have a unit acceptance test where I am mocking the creation of a user.

class UserAcceptanceApiTest extends TestCase
{
    use WithoutMiddleware;

    public function setUp()
    {
        parent::setUp();

        $this->User = factory(App\Models\User::class)->make([
            'id' => '999',
            'name' => 'Name',
            'email' => 'test@example.com',
            'password' => bcrypt('password'),
        ]);
        $this->User = factory(App\Models\User::class)->make([
            'id' => '999',
            'name' => 'Name',
            'email' => 'test@example.com',
            'password' => bcrypt('password'),
        ]);
        $user = factory(App\Models\User::class)->make();
        $this->actor = $this->actingAs($user);
    }



    public function testStore()
    {
        $response = $this->actor->call('POST', 'api/users', $this->User->toArray());
        $this->assertEquals(200, $response->getStatusCode());
        $this->seeJson(['id' => 999]);
    }

}

I get the following exception "Field 'password' doesn't have a default value.

This is because in my User model I have the following:

protected $hidden = ['password', 'remember_token'];

So it automatically removes the password field from the JSON.

Is there a way I can override this only for this test? As I want to keep the password as a hidden attribute.



via Chebli Mohamed

Laravel - Domain API?

I'm trying to figure something out. I want to make a page where a user can check for domain names and if they're available or not. I'm asking for advice because I don't know where to look. TransIP does have an API but I can't understand their documentation. What can I do? I want to make this work in laravel



via Chebli Mohamed

Best Practice for pulling data in Laravel

I'm relatively new with Laravel and I'm learning as well as working on Laravel based projects.

My question is what are Laravel Model/Eloquent Best Practices:

Is it better to pull records from the database this way Where I have only one function in my user Model like 'staff()':

$managers = $users->staff()->where('usertype', manager');

Or is better to pull records from the database this way Where I have multiple functions in my user Model like 'staff()', 'managers()', 'clerks()':

$managers = $users->managers();
$clerks = $users->clerks();

So basically, I'm asking if Such database related logic should be handled on Model end or Controller end?

PS: I'm on Laravel 5.5



via Chebli Mohamed

Add data into laravel object

so i have this kind of class from my user controller

public function index()
    {
        $table_data = User::with('CU','pus')->select('id','id_cu','id_pus','name','username','gambar','status','created_at')->filterPaginateOrder();

        return response()
            ->json([
                'model' => $table_data
            ]);
    }

it is using trait called filterPaginateOrder and the end result that i receive are:

{
  "model": {
    "current_page": 1,
    "data": [
      {
        "id": 8,
        "id_cu": 0,
        "id_pus": 1,
        "name": "test1",
        "username": "test17",
        "gambar": "",
        "status": 1,
        "created_at": "2018-02-27 06:37:10",
        "c_u": null,
        "pus": {
          "id": 1,
          "name": "Puskopdit BKCU Kalimantan"
        }
      },
      {
        "id": 1,
        "id_cu": 0,
        "id_pus": 1,
        "name": "tony",
        "username": "t0n1zz",
        "gambar": null,
        "status": 1,
        "created_at": "2017-01-01 11:11:11",
        "c_u": null,
        "pus": {
          "id": 1,
          "name": "Puskopdit BKCU Kalimantan"
        }
      }
    ],
    "from": 1,
    "last_page": 1,
    "next_page_url": null,
    "path": "https://bkcuvue.dev/api/v1/user",
    "per_page": "2",
    "prev_page_url": null,
    "to": 2,
    "total": 2
  }
}

so what if i want to add some data into it? inside data array for each array i want to add "role":"master" how do i do that?

i tried $table_data->push('role','master') and $table_data->put('role','master') from reading about collection (those query in laravel return collection right?) but none of those code working...



via Chebli Mohamed

how to reduce TTFB(time to first byte) and my websites TTFB time is 37s

screenshot for TTFB

Any help will be appreciated Thank you in advance



via Chebli Mohamed

Shorthand if/else php not continue

How to get to the next argument event if the second or third is false ? in my case gender is false but marital status is true but they stop at gender and not execute marital status. how can I make it continue to next argument event second or third is false ?

public function creditScore($user, $basic_information)
    {
        $basic_information->birth_date ? dispatch(new CalculateAge($user)) : false;
        $basic_information->dependents ? dispatch(new CalculateDependents($user)) : false;
        $basic_information->education ? dispatch(new CalculateEducation($user)) : false;
        $basic_information->gender ? dispatch(new CalculateGender($user)) : false;
        $basic_information->marital_status ? dispatch(new CalculateMaritalStatus($user)) : false;
    }



via Chebli Mohamed

Explaining advance search trait in laravel and flatten object

i have learn this kind of trait for advanced searching from this github project with laravel backend project with vuejs as the front end framework (SPA project) but it did not given any explanation and now when i need something quite different from the example project, i facing problem.

So i hoping someone in here can help me understand this trait for searching, it retrieving this kind of get request

https://bkcuvue.dev/api/v1/user?column=id&direction=desc&per_page=2&page=1&search_column=name&search_operator=like&search_query_1=&search_query_2=

and as the url given, there is column parameter for specifying which column in the query that use for sorting, and then there is direction for controlling sorting (ascending or descending).

and then there is per_page to determine how many row being retrieving at the get call, and then there is page for pagination.

and there is search_column for which column being used for searching with coresponding search_operator for searching operator (like,between,equal, etc) and 2 search_query that use for user inputing keyword for searching.

and to make this kind of get url work i need to add this trait

<?php 

namespace App\Support;

use Validator;

trait FilterPaginateOrder {

    protected $operators = [
        'equal_to' => '=',
        'not_equal' => '<>',
        'less_than' => '<',
        'greater_than' => '>',
        'less_than_or_equal_to' => '<=',
        'greater_than_or_equal_to' => '>=',
        'in' => 'IN',
        'not_in' => 'NOT_IN',
        'like' => 'LIKE',
        'between' => 'BETWEEN'
    ];

    public function scopeFilterPaginateOrder($query)
    {
        $request = request();

        $v = Validator::make($request->all(), [
            'column' => 'required|in:'.implode(',', $this->filter),
            'direction' => 'required|in:asc,desc',
            'per_page' => 'required|integer|min:1',
            'search_operator' => 'required|in:'.implode(',', array_keys($this->operators)),
            'search_column' => 'required|in:'.implode(',', $this->filter),
            'search_query_1' => 'max:255',
            'search_query_2' => 'max:255'
        ]);

        if($v->fails()) {

            //for debug
            // dd($v->messages());
        }

        return $query->orderBy($request->column, $request->direction)
            ->where(function($query) use ($request) {
                // check if search query is empty
                if($request->has('search_query_1')) {
                    // determine the type of search_column
                    // check if its related model, eg: customer.id
                    if($this->isRelatedColumn($request)) {
                        list($relation, $relatedColumn) = explode('.', $request->search_column);
                        return $query->whereHas($relation, function($query) use ($relatedColumn, $request) {
                            return $this->buildQuery(
                                $relatedColumn,
                                $request->search_operator,
                                $request,
                                $query
                            );
                        });
                    } else {
                        // regular column
                        return $this->buildQuery(
                            $request->search_column,
                            $request->search_operator,
                            $request,
                            $query
                        );
                    }
                }
            })
            ->paginate($request->per_page);
    }

    protected function isRelatedColumn($request)
    {
        return strpos($request->search_column, '.') !== false;
    }

    protected function buildQuery($column, $operator, $request, $query)
    {
        switch ($operator) {
            case 'equal_to':
            case 'not_equal':
            case 'less_than':
            case 'greater_than':
            case 'less_than_or_equal_to':
            case 'greater_than_or_equal_to':
                $query->where($column, $this->operators[$operator], $request->search_query_1);
                break;
            case 'in':
                $query->whereIn($column, explode(',', $request->search_query_1));
                break;
            case 'not_in':
                $query->whereNotIn($column, explode(',', $request->search_query_1));
                break;
            case 'like':
                $query->where($column, 'like', '%'.$request->search_query_1.'%');
                break;
            case 'between':
                $query->whereBetween($column, [
                    $request->search_query_1,
                    $request->search_query_2
                ]);
                break;
            default:
                throw new Exception('Invalid Search Operator', 1);
                break;
        }

        return $query;
    }
}

and then to make it works with our model then we need to add it into our model

<?php

namespace App;

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Support\FilterPaginateOrder;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles, HasApiTokens, Notifiable, FilterPaginateOrder;

    protected $table = 'users';

    public static $rules = [
        'name' => 'required|min:5',
        'email' => 'required|email',
        'username' => 'required|min:5',
        'password' => 'required|min:5',
    ];

    protected $fillable = [
        'id_pus','id_cu','name','email','username', 'password','gambar','status'
    ];

    protected $filter = [
        'id','id_cu','id_pus','name','email','username','gambar','status','created_at'
    ];

    public function getNameAttribute($value){
        return !empty($value) ? $value : '-';
    }

    public static function initialize()
    {
        return [
            'id_cu' => '0' , 'id_pus' => '0', 'name' => '','email' => '', 'username' => '', 'status' => '0', 'gambar' => ''
        ];
    }

    protected $hidden = [
        'password', 'remember_token',
    ];

    // protected $casts = [
    //     'status' => 'boolean',
    // ];

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

    public function pus(){
        return $this->belongsTo('App\Pus','id_pus','id')->select('id','name');
    }

    public function CU(){
        return $this->belongsTo('App\CU','id_cu','id')->select('id','name');
    }
}

and then in my controller (which in this example is usercontroller) will be like this

public function index()
{
    $table_data = User::with(array('CU','pus','roles' => function($query){
            $query->select('name');
        }))->select('id','id_cu','id_pus','name','username','gambar','status','created_at')->filterPaginateOrder();

    return response()
        ->json([
            'model' => $table_data
        ]);
}

then it will return

{
  "model": {
    "current_page": 1,
    "data": [
      {
        "id": 8,
        "id_cu": 0,
        "id_pus": 1,
        "name": "test1",
        "username": "test17",
        "gambar": "",
        "status": 1,
        "created_at": "2018-02-27 06:37:10",
        "c_u": null,
        "pus": {
          "id": 1,
          "name": "Puskopdit BKCU Kalimantan"
        },
        "roles": [
          {
            "name": "CU Akses Penuh",
            "pivot": {
              "model_id": 8,
              "role_id": 2
            }
          }
        ]
      },
      {
        "id": 7,
        "id_cu": 0,
        "id_pus": 1,
        "name": "test1",
        "username": "test16",
        "gambar": "",
        "status": 1,
        "created_at": "2018-02-27 06:36:06",
        "c_u": null,
        "pus": {
          "id": 1,
          "name": "Puskopdit BKCU Kalimantan"
        },
        "roles": [

        ]
      }
    ],
    "from": 1,
    "last_page": 4,
    "next_page_url": "https://bkcuvue.dev/api/v1/user?page=2",
    "path": "https://bkcuvue.dev/api/v1/user",
    "per_page": "2",
    "prev_page_url": null,
    "to": 2,
    "total": 8
  }
}

now the question is

  1. i don't quite understand how this all code works.... and it giving me trouble when i want a quite specific result like in my second question below
  2. as you can see in the json data, the data returned with roles array that contain multiple object and i have no idea how to use those roles for searching the roles name or for sorting roles name according to those trait, i tried to make it like in pus relationship table by using pus.name as search_column parameter but when i tried it to roles relationship roles.name it just not working


via Chebli Mohamed

In laravel 5.4 how can i get only the users friends posts?

$user_id = auth::user()->id;
$user_friends = User::find($user_id)->friends;
$user_friends_id = $user_friends->pluck('id');
$posts = Post::where('user_id', $user_friends_id)->get();
return view('dashboard')->with('posts', $posts);

So far i've got the users friends id's in $user_friends_id and then matching them to the user id on the posts but its only getting the first friends posts and not the rest. How can i change it to get all the friends posts and not just the first friends?



via Chebli Mohamed

Where condition in laravel eloquuent

How can i write the the following query in laravel eloquent

"SELECT TITLE, AUTHOR FROM book1 where (Title like 'computer or Subject like computer ) NOT (imprint like 'delhi' or series like 'abc')

i connect the query with logical operator "NOT". How can I



via Chebli Mohamed

laravel db sql query or

this my laravel query

$Product = Product::select('id','ProductWorkpiece','ProductCategory','ProductName','ProductImage','ProductSubCategory')
        ->where('ProductCategory',$category)
        ->where(function ($query) use ($ProductWorkpiece,$ProductMaterial,$ProductSubCategory,$ProductBrand) {

     foreach($ProductBrand as $key => $ProductBrandd) {
                if (!empty($ProductBrandd) && empty($subcategory)) {
                $query->orWhere('ProductBrand', '=', $ProductBrandd);
                    }
                 foreach($ProductSubCategory as $key => $subcategory) {
                if (!empty($ProductBrandd) && !empty($subcategory)) { 
                  $query->where('ProductSubCategory', '=', $subcategory);
                        }
                    }
                }
    })->where('Status','=','1')->get();

actually works but there is a strange one, when i click 1 check box works but when i click to 2 why not work by example I have a brand with the name sisma and have 2 product subcategory with the name Laser Marking Machine brand sisma when I checked brand sisma, out 2 product and when I checked the subcategory Dot Marking Machine and both items are missing. and that's right and when I checked the subcategory Laser Marking Machine and 2 the product did not come out and when I unchecked the Dot Marking Machine stuff came out and I call it strange that it should be without unchecked can be seen 2 product

if you still dont understand, watch this video is only 12 seconds https://youtu.be/fY417NsZmHI

and this is my manual sql ,it works well

SELECT * FROM Product WHERE ProductCategory = 'Marking' AND ProductBrand = 'Sisma' and ProductSubCategory = 'Dot Marking Machine' 
or ProductSubCategory = 'Laser Marking Machine' 

thanks for help



via Chebli Mohamed

Laravel 5.5: How to protect the register route in a stateles API and make sure that a real person is trying to register throught a mobile app?

I want to protect my register route so only real users of mobile applications can register and I will not get spamed with thousands request for registration. I know laraval takes care of this throught csrf token but that is only for web applications where we have sessions. How about stateles Api? How can i exchange an application token when the user is trying to register for the first time from mobile application?



via Chebli Mohamed

How to find out if the hour has passed?

I have fuild timestamps in mysql db How to find out if the hour (Carbon::now()) passed from timestamps ?



via Chebli Mohamed

Pass a View Data From Controller to Ajax View File - Laravel 5

From View Page I am calling Ajax to my Controller, from my Controller I want to create a html data so I am passing my array to View file to create a HTML data. I don't know why when I try to do console nothing gets return, can anyone tell me where I am going wrong

CallingAjaxFromViewFile

function AjaxgetCheckInChekOutUser(status){
    var url = "";
    var token = $('#token').val();
    if(status){
        $.ajax({
                headers: {
                'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
                },
                url: url,
                type: 'POST',
                data: {'status': status,'_token':token},            
                success: function (data) {
                    alert(data);
                    data = JSON.parse(data);      
                        console.log(data.html);
                        $('#gymimages').html(data.html);

                }
        });
    }
}

myControllerFile

public function AjaxCurrentPastFutureData($data, $status){
 $title = "HDTuto.com";  

        $html = view('admin.events.ajaxdataview')->with(compact('title'))->render();
        //pr($html);
        $response = response()->json(['success' => true, 'html' => $html]);
        return $response;
}

NowmyViewFile From Where I append HTML Data

<h1><i> </i></h1>

Can anyone tell me where I am going wrong?



via Chebli Mohamed

Currently unable to handle this request. HTTP ERROR 500 when i deployed my laravel 5.5 application

I tried deploying my laravel application to my sub domain test.domain.com. I uploaded my files inside Public_html/test folder then i moved all the files inside public folder to the root folder test folder. After that i changed the credentials in my index.php:

before:

require __DIR__.'/../vendor/autoload.php';
$app = require_once __DIR__.'/../bootstrap/app.php';

now:

require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';

When i tried visiting the website i get this error:

test.domain.com is currently unable to handle this request. HTTP ERROR
500

I found this error in the error_log file:

 PHP Parse error: syntax error, unexpected '?' in vendor/laravel/framework/src/Illuminate/Foundation/helpers.php on line 233

My site has SSL and The Php version is 7.2

Any help would be appreciated. Thanks.



via Chebli Mohamed

mardi 27 février 2018

Laravel Controller : How to use function store and create

I am currently new to laravel and working on a basic project where a service provider (SP) is able to post service details by filling up form.

enter image description here

I am trying to check if SP has uploaded a featured image. if yes, then rename file by using $featured = $request->featured; $featured_new_name = time().$featured->getClientOriginalName(); $featured->move('uploads/services', $featured_new_name); and saving it to 'uploads/services/' directory.

my ServiceController.php looks like this

public function store(Request $request)
{
      $this->validate($request, [
      'name' => 'required|max:255',
      'address' => 'required|max:255',
      'city' => 'required|max:255',
      'state' => 'required|max:255',
      'zipcode' => 'required|integer|digits:5',
      'category_id' => 'required',
      'workingday' => 'required',
      'content' => 'required'
      ]);
//checking if featured image (logo file) is uploaded or not 

    if($request->hasfile('featured'))
  {
    $featured = $request->featured;
    $featured_new_name = time().$featured->getClientOriginalName();
    $featured->move('uploads/services', $featured_new_name);
  }
  else {      }

     $featured->move('uploads/services', $featured_new_name);

      $service = Service::create([
      'name' => $request->name,
      'content' => $request->content,
      'address' => $request->address,
      'city' => $request->city,
      'state' => $request->state,
      'zipcode' => $request->zipcode,
      ]);

      if($request->hasfile('featured'))
      {
        $service = Service::create([
        'name' => $request->name,
        'content' => $request->content,
        'featured' =>'uploads/services/'.$featured_new_name,
        'address' => $request->address,
        'city' => $request->city,
        'state' => $request->state,
        'zipcode' => $request->zipcode,
    ]);
 }
    $service->workingdays()->attach($request->workingday);
    $service->categories()->attach($request->category_id);
    $service->user_id=auth()->id();
    $service->save();

  Session::flash('success','Service created successfully');
  return view('sp.services.create')->with('categories', Category::all())->with('workingday', Workingday::all());
}

I am saving logged in user_id along with all other service details. When user uploads logo file this code stores two records in database one with correct user_id and one with 0.

enter image description here

Here user_id 2 is correct entry. Please help me improve this code.

Thanks in advance.



via Chebli Mohamed

Laravel webpack.mix - Error when using copy()

This is my webpack.mix:

let mix = require('laravel-mix');
mix.copyDirectory('resources/assets/bower/card-js/src', 'public/plugins/card-js');

When I run npm run dev the dir is copied, but after before the commands ends I get this error:

C:\Apache24\desarrollo\facturador\node_modules\graceful-fs\polyfills.js:144
        throw er
        ^

Error: ENOENT: no such file or directory, read
    at Object.fs.readSync (fs.js:675:18)
    at Object.readSync (C:\Apache24\desarrollo\facturador\node_modules\graceful-fs\polyfills.js:138:28)
    at copyFileSync (C:\Apache24\desarrollo\facturador\node_modules\fs-extra\lib\copy-sync\copy-file-sync.js:28:20)
    at copySync (C:\Apache24\desarrollo\facturador\node_modules\fs-extra\lib\copy-sync\copy-sync.js:43:5)
    at contents.forEach.content (C:\Apache24\desarrollo\facturador\node_modules\fs-extra\lib\copy-sync\copy-sync.js:54:7)
    at Array.forEach (<anonymous>)
    at copySync (C:\Apache24\desarrollo\facturador\node_modules\fs-extra\lib\copy-sync\copy-sync.js:51:14)
    at contents.forEach.content (C:\Apache24\desarrollo\facturador\node_modules\fs-extra\lib\copy-sync\copy-sync.js:54:7)
    at Array.forEach (<anonymous>)
    at Object.copySync (C:\Apache24\desarrollo\facturador\node_modules\fs-extra\lib\copy-sync\copy-sync.js:51:14)
    at File.copyTo (C:\Apache24\desarrollo\facturador\node_modules\laravel-mix\src\File.js:210:12)
    at FileCollection.copyTo (C:\Apache24\desarrollo\facturador\node_modules\laravel-mix\src\FileCollection.js:88:24)
    at src.forEach.file (C:\Apache24\desarrollo\facturador\node_modules\laravel-mix\src\FileCollection.js:82:38)
    at Array.forEach (<anonymous>)
    at FileCollection.copyTo (C:\Apache24\desarrollo\facturador\node_modules\laravel-mix\src\FileCollection.js:82:17)
    at CopyFilesTask.run (C:\Apache24\desarrollo\facturador\node_modules\laravel-mix\src\tasks\CopyFilesTask.js:14:20)
    at CustomTasksPlugin.runTask (C:\Apache24\desarrollo\facturador\node_modules\laravel-mix\src\plugins\CustomTasksPlugin.js:34:14)
    at Mix.tasks.forEach.task (C:\Apache24\desarrollo\facturador\node_modules\laravel-mix\src\plugins\CustomTasksPlugin.js:9:44)
    at Array.forEach (<anonymous>)
    at Compiler.compiler.plugin.stats (C:\Apache24\desarrollo\facturador\node_modules\laravel-mix\src\plugins\CustomTasksPlugin.js:9:23)
    at Compiler.applyPlugins (C:\Apache24\desarrollo\facturador\node_modules\tapable\lib\Tapable.js:61:14)
    at emitRecords.err (C:\Apache24\desarrollo\facturador\node_modules\webpack\lib\Compiler.js:264:11)
    at Compiler.emitRecords (C:\Apache24\desarrollo\facturador\node_modules\webpack\lib\Compiler.js:371:38)
    at emitAssets.err (C:\Apache24\desarrollo\facturador\node_modules\webpack\lib\Compiler.js:258:10)
    at applyPluginsAsyncSeries1.err (C:\Apache24\desarrollo\facturador\node_modules\webpack\lib\Compiler.js:364:12)
    at next (C:\Apache24\desarrollo\facturador\node_modules\tapable\lib\Tapable.js:218:11)
    at Compiler.compiler.plugin (C:\Apache24\desarrollo\facturador\node_modules\webpack\lib\performance\SizeLimitsPlugin.js:99:4)
    at Compiler.applyPluginsAsyncSeries1 (C:\Apache24\desarrollo\facturador\node_modules\tapable\lib\Tapable.js:222:13)
    at Compiler.afterEmit (C:\Apache24\desarrollo\facturador\node_modules\webpack\lib\Compiler.js:361:9)
    at require.forEach.err (C:\Apache24\desarrollo\facturador\node_modules\webpack\lib\Compiler.js:350:15)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/we
bpack.config.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

I have reinstalled nodejs and npm a couple of times and the error persists, but just for copy() and copyDirectory(). For example, if I have this:

let mix = require('laravel-mix');
mix.sass('resources/assets/sass/theme.scss', 'public/css/theme.css');

If I run npm run dev everything compiled correctly without errors. I just need a little help in find why is not compiling when coping content. Thank you in advance.



via Chebli Mohamed

Creating a row in two tables with one form. How do I add IDs connecting them?

I'm using laravel 5.6 and I'm trying to insert a row into two different tables and link them together inside public function store()

Here's what I have:

public function store(Request $request)
    {
        $this->validate($request, [
          'name'         => 'required',
          'email'        => 'required',
          'project'      => 'required',
          'project_type' => 'required',
          'budget'       => 'required'
        ]);

        $client = new Client;
        $project = new Project;

        $client->name       = $request->input('name');
        $client->email      = $request->input('email');
        $client->save();

        $project->project      = $request->input('project');
        $project->project_type = $request->input('project_type');
        $project->budget       = $request->input('budget');
        $project->save();

        return redirect('/admin/clients');
    }

I need to do something like:

$client->project_id = $project->id;
$project->client_id = $client->id;

But that obviously won't work. How would I go about getting IDs for these rows whenever the rows haven't been created yet to access them? Is it possible? If not I'll find a work around or approach it a different way.

Thanks.



via Chebli Mohamed

How to save Quill.js values to Database Laravel 5.6

I'm trying to use Quill.js - Your Powerful Rich Text Editor for my project in laravel.

But, since quill uses:

<div id="editor"></div> || <div id="editor" name="body"></div>

Instead of a regular old:

<textarea id="editor" name="body"></textarea>

$post->body = $request->input('body'); won't work.

What do I use to save the information I get from a div with the id of #editor into a database.

Thanks



via Chebli Mohamed

how to remove SimpleXMLElement Object

How can i delete " SimpleXMLElement Object" from the following array

Array ( [0] => SimpleXMLElement Object ( [0] => IVA ) ) Array ( [0] => SimpleXMLElement Object ( [0] => 566.90 ) )

i have this code in my Controller

 $count=0;
foreach ($xml->xpath('//cfdi:Comprobante//cfdi:Impuestos//cfdi:Traslados//cfdi:Traslado') as $nodo){                                                                        




        $importes[] = $nodo['importe'];
        $impuestos[] = $nodo['impuesto'];
        $count++;


            }

                    $num_elementos[]=$count;


    $limite_prueba=count($num_elementos);

    $corte = 0;


    for ($x=0;$x<$limite_prueba;$x++){

        $salida = array_slice($importes, $corte, $num_elementos[$x]);
        $salida_imp = array_slice($impuestos, $corte, $num_elementos[$x]);

        $resultado = array_unique($salida);
        $resultado2 = array_unique($salida_imp);



                print_r($resultado2);
                print_r($resultado);
            echo "<br>";


                $corte = $corte + $num_elementos[$x];



    }



via Chebli Mohamed

redirect in Auth/LoginController

I am trying to redirect the user from the auth/login to a uri that I have stored in a session var. I am trying to override the redierectTo method found in Auth/LoginController (or at least I think that's how its done), but it keeps on redirecting to the /home page.

I have tried using the constructor like

protected $redirectTo = '';

public function __construct()
  {
    $this->middleware('guest')->except('logout');
    $this->redirectTo = Session::get('uri');
}

but it redirects to the /home page

I've tried to override the redirectTo method like so:

 protected function redirectTo()
  {

     return Session::get('uri');
  }

also redirects to the /home page

I've tried overriding the redirectPath method of the redirectPath in the RedirectIfAuthenticated file:

protected function redirectPath()
  {

     return Session::get('uri');
  }

Still redirects to the /home page

I've tried to change the redirect('/home') to redirect(Session::get('uri')) in the RedirectIfAuthenticated middleware

 public function handle($request, Closure $next, $guard = null)
  {
    if (Auth::guard($guard)->check()) {
        return redirect(Session::get('uri'));
    }

    return $next($request);
  }

still redirects to the /home page

I'm stumped any help greatly appreciated. Thanx in advance



via Chebli Mohamed

Laravel 5.6 Eloquent ORM where join table

I am dealing with Eloquent ORM collections and query builders. I am trying to figure out how to join and use "where" in a collection, like in query builder.

For example, I have the following tables:

Users:

ID  |  Name  |  Last name
-------------------------
 1  | Martin | Fernandez
 2  | Some   | User

Persons:

ID  |  Nick  |  User_ID  |  Active
----------------------------------
 1  | Tincho | 1         |  1

Companies:

ID  | Name   | User_ID   |  Active
----------------------------------
 1  | Maramal| 1         |  0
 2  | Some   | 2         |  1

This is an example, the tables I am working on have more than 30 columns each one. I want to select all the user that are active.

Usually I would do a query like:

SELECT *
FROM users
LEFT JOIN persons ON users.id = persons.user_id
LEFT join companies ON users.id = companies.user_id
WHERE persons.active = 1
OR companies.active = 1

That can be translated to Laravel Query Builder like:

DB::table('users')
   ->leftJoin('persons', 'users.id', '=', 'persons.user_id')
   ->leftJoin('companies', 'users.id', '=', 'companies.user_id')
   ->where('persons.active', 1)
   ->orWhere('companies.active', 1)
   ->get(); 

But what I want to use is a Laravel Eloquent ORM Collection, until now I am doing the following:

$users= User::orderBy('id',' desc')->get();

foreach($users as $k => $user) {
    if($user->company && !$user->company->active || $user->person && !$user->person->active) {
        unset($users[$k]);
    }
    ... and here a lot of validations and unsets ...
 }

But I know that at this point, I already grabbed all the users instead those who are active.

How would I achieve what I did with query builder within a collection? Thanks in advance.



via Chebli Mohamed

Laravel Permanent Redirect

We are about to migrate our company website from standard .php website to Laravel. We kept the same url structure except that the new url's don't use .php at the end of the file name.

We want to allow our customers to still use the old url ( www.oursite.com/faq.php ) with the .php at the end, but redirect them to the new clean url without the .php ( http://dev2.goverlan.com/faq ) if our users paste the old url in the browser address bar.

Any ideas in how to do this?



via Chebli Mohamed

Laravel Model Restore Event

So I have 2 Models Users & Staff. They have one to one relationship with one another.

User.php 'hasOne' Staff AND Staff.php 'belongsTo' User

When I Soft Delete a User I want to soft delete Staff entry as well, I have achieved this using(Works Perfectly):

static::deleting(function ($user) {
    $user->staff()->delete(); 
});

Now I want to restore the staff when I restore the User for that I have tried using this(Not working):

static::restoring(function ($user) {
    $user->staff()->restore();
});

But this is not working. The User Entry is deleted but the Staff entry still remains soft deleted.

  • Can someone help me understand what I am doing wrong here?

  • Also, Is this the best way to get this done? Or is there some other way this should be done?

PS: I'm using Laravel 5.5



via Chebli Mohamed

Instagram Integration on Laravel 5

I kept getting this issue after installing this package below

https://github.com/vinkla/instagram

into my Laravel 5.1 project.

2018-02-27 at 1 55 36 pm

I followed everything in the instruction.

I am on Mac OS X, PHP 7.1, Laravel 5.1

Did I forget something?

How would one go about and debug this further ?


I'm open to any suggestions at this moment.

Any hints/suggestions / helps on this be will be much appreciated!



via Chebli Mohamed

how to send variable from controller to another controller that is used in form

I have two controllers one for Posts and another for section

I want to create posts form create.blade.php and display sections that I have created from addSection.blade.php when I use variable I get undefined variable !

again what I want to achieve here is to create posts and in create posts page I want to display sections so the user can select and post posts to specific section.

class PostController extends Controller {

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    //

    $posts = Post::orderBy("created_at","desc")->paginate(2);
     return view('index')->with('posts',$posts);

}

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


/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    //
    $request->validate([
        'progName' => 'required|unique:posts|max:255',
        'description' => 'required',
        'postImg' => 'image|nullable|max:1024',
    ]);

    if ($request -> hasFile('postImg')) {
        # code...
        $fileNameWithExtention = $request ->file('postImg')->getClientOriginalName();
        $fileName = pathinfo($fileNameWithExtention,PATHINFO_FILENAME);
        $extention = $request -> file('postImg')->getClientOriginalExtension();
        $fileNameStore = $fileName . '__'.time().'.' .$extention;
        $path =  $request ->file('postImg')->storeAs('public/postimage',$fileNameStore);
    }else{
        $fileNameStore = 'noimage.jpg';
    }

    $post = new Post;
    $post -> progName = $request->input('progName');
    $post -> version = $request->input('version');
    $post -> OperatingSystems = $request->input('OperatingSystems');
    $post -> description = $request->input('description');
    $post -> link = $request->input('link');
    $post -> postImage =  $fileNameStore;
    $post -> UserIdForPost = auth()->user()->id;
    $post -> save();



    return redirect('/home/') -> with(['success' => 'Done ^__^ ' ]);

}

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    //
}

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

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

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

}

also i hade make anothe Controller to Handel sections ( is this right ? )

class sections extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $sections = Section::orderBy("created_at","desc")->paginate(2);
        return view('/addSections')->with('sections',$sections);
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        $sections = new Section;
        $sections -> sectionName = $request->input('sectionName');
        $sections -> save();
        return redirect('/home/') -> with(['success' => 'Done ^__^ ' ]);

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
        $sections =  Section::find($id);
        return view('/create')->with('sections',$sections);

    }

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

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

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

and this is my addSection.blade.php

<form action="" method="post" enctype="multipart/form-data">

    <div class="card border-secondary col-4">
        <div class="card-header">Add Sections</div>
        <div class="card-body">

            <div class="form-group ">

                <label for="sectionName"><h4 class="card-title" style="text-align: center">Section Name</h4></label>
                <input name="sectionName" type="text" class="form-control" placeholder="program name...">


            </div>
            <button type="submit" class="btn btn-warning">Click Me</button>
        </div>
    </div>

    

</form>

and in another page ( create.blade.php ) i use this action this page i use to create posts action="



via Chebli Mohamed

How to add custom action in laravel backpack with crud request?

Created controller actions

public function publish(PublishArticleRequest $request)
{
    $id = $request->get('id');
    /**
     * @var Article $article
     */
    $article = $this->crud->getEntry($id);
    $article->publish();
    die;
    return back();
}

public function unpublish(PublishArticleRequest $request)
{
    $id = $request->get('id');
    /**
     * @var Article $article
     */
    $article = $this->crud->getEntry($id);
    $article->unpublish();
    $article->save();
    return back();
}

and button

return sprintf(
            '<a href="%s" class="btn btn-xs btn-default">'
            . '<i class="fa fa-fw fa-' . $icon . '"'
            . ' title="' . $title . '"'
            . ' data-toggle="tooltip"'
            . ' data-placement="top"'
            . '></i>'
            . '</a>',
            e(route('crud.article.' . $action, ['id' => $article->getKey()]))
        );

and request

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'id' => 'required|integer',
        ];
    }
}

and finally route

Route::get('article/{id}/publish', ArticleCrudController::class . '@publish')
    ->where(
        [
            'id' => '[0-9]+'
        ])
    ->name('crud.article.publish');
Route::get('article/{id}/unpublish', ArticleCrudController::class . '@unpublish')
    ->where(
        [
            'id' => '[0-9]+'
        ])
    ->name('crud.article.unpublish');

But publish method in controller is not called. What i forgot? I need add acl-check and csrf-check, but this does not work even without the above checks.

Spam a little - stackoverflow wants more text in question, I didnt know what to say except what was already said, so I wrote this text, just for stackoverflow checking. Sorry for that.



via Chebli Mohamed

Laravel Queues and 'max_user_connections' Error

I have implemented database queue on a shared hosting using cron job

/usr/local/bin/ea-php70 /home/path_to_artisan/artisan queue:work --queue=high,default >/dev/null 2>&1

Everything works fine. But after some 1 or 2 hours start getting 'max_user_connections' error when I try to login.

Is this is the correct way to run a queue on shared hosting account



via Chebli Mohamed

In codeignitor how to pass the array variable to next page without store in database


I was posting the values in CodeIgniter and store in array I need the array values in next page is there any possible way to do that (without storing in database)

   function next()
         {   

     if(isset($_POST) && count($_POST) > 0)     
    {  

            $data = array(
                'job_type' => $this->input->post('job_type'),
                'job_partner' => $this->input->post('job_partner'),
                'job_manager' => $this->input->post('job_manager'),
                'job_owner' => $this->input->post('job_owner'),

            );
                      $this->load->view("ca_recuring_job/cust_page", $data);
                    redirect(base_url()."ca_recuring_job/cust_page".$data);
                        }else{
           $data['_view'] = 'ca_recuring_job/add';
           $this->load->view('layouts/main',$data);
    } 

   }

i need array values in next page without storing into database if anybody come over this please help me. thanks in advance



via Chebli Mohamed

how to implement an AND logical operator type of validation in laravel

I want to know how to implement a type of validation whereby an error will only occur if both fields have had the exact input before.

For example: if username: Andy Roddick division: New York is already in the database,

username: Andy Roddick division: Texas is fine,

username: Lebron James division: New York is fine,

but username: Andy Roddick division: New York will throw an error.

This is the code i'm using.

$this->validate($request, [
        'username' =>'required',
        'division' =>'required',
     ]);



via Chebli Mohamed

Laravel Socialite throws ClientException or InvalidStateException only in production

I have for the last 8 hours tried to fix a login problem with Laravel Socialite that only accurs when i'm on production server (Ubuntu 16 and LEMP stack). The login with Socialite works on localhost. I'm using Laravel 5.5 and Socialite 3.0.

The problem is when Facebook redirects back with the code and state params and Socialite tries to get the token. The url below gives the 500 error..

https://website.com/auth/facebook/callback?code=AQA-KiBJG3Ge_3DqktPGjpjrqIbmOy2Q4f6nW...&state=V9uOnjYU6cOHu0rbs...

Controller:

public function redirectToProvider($provider)
{

    return Socialite::driver($provider)->scopes(['user_birthday', 'user_work_history', 'user_education_history'])->redirect();
}

public function handleProviderCallback($provider)
{

    $user = Socialite::driver($provider)->user(); //Where error is thrown

    session()->put('fb_token', $user->token);

}

Using the handler with Socialite::driver($provider)->user(); throws..

    (1/1) InvalidStateException
    in AbstractProvider.php (line 209)
    at AbstractProvider->user()
    in LoginController.php (line 65)
    at LoginController->handleProviderCallback('facebook')
    ...

When I change the handler to Socialite::driver($provider)->stateless()->user(); it throws

(1/1) ClientException
Client error: `POST https://graph.facebook.com/v2.10/oauth/access_token` resulted in a `400 Bad Request` response:
{"error":{"message":"Missing authorization code","type":"OAuthException","code":1,"fbtrace_id":"hghkl145"}}
in RequestException.php (line 113)
at RequestException::create(object(Request), object(Response))
in Middleware.php (line 65)
at Middleware::GuzzleHttp\{closure}(object(Response))
in Promise.php (line 203)
at Promise::callHandler(1, object(Response), array(object(Promise), object(Closure), null))
in Promise.php (line 156)
...

It feels like I have tried everything from the forums like SERVICE_DOMAIN in services.php, ngix settings, stateless(), clear cache, doublecheck facebook panel setting, .env file etc but it won't work..



via Chebli Mohamed

FTP changes not showing in Browser laravel

I am using FileZilla to transfer files in my Laravel application.

I view/edit a file from the cloudways server in my local IDE, make changes, save, close and add the file back to the cloudway servers. I am prompted with the dialog box which states the file already exist and I choose to overwrite existing server file. Also, I view the file again and I see my change. So I know for sure the modified file was uploaded to the server.

I also restarted services such as apache, memcached, mysql, nginx. In addition, I purged varnish and finally disabled varnish. Last but not least I restarted the server and still the new changes are not reflecting in the browser.

I don't have a domain. I am using the cloudways generated app url. I tried to access the application in multiple browsers on different PCs and mobile device and no avail.

I tried these commands but not showing changes.

I can see the changes in my localhost but it does not appear when I upload it to the server.

php artisan clear:cache
php artisan config:clear
php artisan view:clear
npm clear:cache --force

Any help will be appreciated.

Thank you,



via Chebli Mohamed

Delete specific jobs from Queue - Database driver

I am using database driver for managing the queue jobs, let's say there are 300 jobs in queue which are running and jobs are associated with users, now I want to delete jobs for a specific user how can I do that using database driver ?

I read InteractsWithQueue trait helps to interact with the queue and delete the jobs but I am not sure how to delete any specific job. Any help would be appreciated.



via Chebli Mohamed

Laravel Angularjs Theme

Hi anybody have laravel theme with backend as Laravel frontend as Anhuarjs(1) with simple them like login, register & CURD

I try backend i can't able to create or suggest me any github url



via Chebli Mohamed

IGDB using in Laravel

if anyone use the IGDB Api can you explain me how I can use it meaningful with Laravel.

I don't know how to search a field with where statement or something. For example I want to sort games by release date in pagination.

Thanks for answers



via Chebli Mohamed

2 dates compare error - PHP [duplicate]

This question already has an answer here:

I am comparing 2 dates and wants to check if the date is current(today),past or future. I don't know bt the data is still coming wrong. Can anyone tell me where I am going wrong?

Here is my code:

<?php
$date1 = date('m-d-Y'); //02-27-2018
$date2 = "02-28-2018";
$dateTimestamp1 = strtotime($date1);
$dateTimestamp2 = strtotime($date2);

if ($dateTimestamp1 > $dateTimestamp2)
{
  echo "Future date";
  //echo "$date1 is newer than $date2";
}
elseif($dateTimestamp1 < $dateTimestamp2)
{
  echo "past Dates";
}
else
{
  echo "today Dates";
}
?>

It Should print past dates instead it is printing today Dates only.



via Chebli Mohamed

Laravel admin pannel how to create

I am using Laravel as a Backend and Angularjs as a Frontend.

I am Using this full package https://github.com/andbet39/tokenAuth for my Local setup AWT authendication it working fine,

How to do admin authendication and redirect to admin page?

How to do in Admin Panel



via Chebli Mohamed

Using php constructor to initiate API class

I was wondering how to use the constructor to initiate the API class I use in the rest of the class. I need it to be self contained to use in separate a controller.

class Coinbase
{
    private $configuration;
    private $client;

    public function __construct($apiKey, $apiSecret)
    {
        $this->configuration = Configuration::apiKey($apiKey, $apiSecret);
        $this->client = Client::create($this->configuration);
    }

    public static function getBitcoinPrice()
    {
        $buyPrice = $this->client->getBuyPrice('BTC-EUR');
        return var_dump($buyPrice);
    }
}

In my controller I call my own Coinbase class like this:

    $coinbase = new Coinbase;
    return $coinbase->getBitcoinPrice();

This gives the following error:

Using $this when not in object context in Coinbase.php (line 23)

What is a good way to solve this and why is $this->client not configured in the function getBitcoinPrice().



via Chebli Mohamed

Variable properties on a variable method

I'm using a third-party package which manipulates images. For basic conversions it accepts a single value:

$image = $this->addMediaConversion('thumb');
$image->width(100);
$image->height(100);

The system I am building has a level of abstraction where I need to define these values from within a config file. I load the config file in as an array. I can then loop through the values in the config file and generate my various conversions.

My config file:

return [
  'thumb' => [
    'width' => 100,
    'height' => 100,
  ],
];

The code to define these conversions from that config:

$definitions = config('definitions');

foreach($definitions as $name => $keys) {
  $image = $this->addMediaConversion($name);

  foreach($keys as $key => $value) {
    $image->$key($value);
  }
}

This works fine for SINGLE values.

However, the package has methods that take multiple properties against a method, for example:

$image = $this->addMediaConversion('thumb');
$image->fit(Manipulations::FIT_FILL, 560, 560);

There are various methods available that have various different acceptable attributes. I'm looking for an *ELEGANT* solution to this. I am able to achieve it by having an array of values in my config file, checking the type, checking the length of that array, and then passing the correct number, but this isn't scalable, easily maintainable nor elegant.

Config:

return [
  'thumb' => [
    'fit' => [Manipulations::FIT_FILL, 560, 560]
  ]
];

Code:

foreach($image_definitions as $name => $keys) {
  // Generate the conversion
  $conversion = $this->addMediaConversion($name);
  // Loop through and define the attributes as they are in the config, things like ->width(), ->height()
  foreach($keys as $key => $value) {
    if(is_array($value))
    {
      // LOOKING FOR A MORE ELEGANT WAY TO DO THE BELOW
      switch(count($value)) 
      {
        case 2:
          $conversion->$key($value[0], $value[1]);
          break;
        case 3:
          $conversion->$key($value[0], $value[1], $value[2]);
          break;
        case 4:
          $conversion->$key($value[0], $value[1], $value[2], $value[3]);
          break;
        case 5:
          $conversion->$key($value[0], $value[1], $value[2], $value[3], $value[4]);
          break;
        case 6:
          $conversion->$key($value[0], $value[1], $value[2], $value[3], $value[4], $value[5]);
          break;
      }
    } else 
    {
      $conversion->$key($value);
    }                
  }
}

What's the best and most elegant solution for this?



via Chebli Mohamed

Laravel beginner, common function in controller (polymorphism)

I have a project, booking facility of hotel rooms, when I'm coding i got a doubt.. Using a controller to manage bookings.. I need a function that wich to check empty rooms available or not (free room).. If free room available then permit to book the room.. I've to check it when

  • displaying rooms
  • dispalying room
  • while booking
  • and also while paying...

where do i write the code.. In bookingController or in middleware or any other places...?



via Chebli Mohamed

how to autofill a form field with only the "tâches" in relation with the chosen "Metier"?

I have this form and then I have in my database a set of "taches" that is linked to each "metier", I want to choose a "metier" in the field and the following field "taches" to propose me to choose only "taches" related to this "metier". Here is my code and my form.I would be very grateful if someone could help me with this.

create.blade.php

@extends('Layouts/app')
@extends('Layouts.master')
@section('content')
@if(count($errors))
<link rel="stylesheet" 

href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>


<div class="alert alert-danger" role="alert">
 <ul>
    @foreach($errors ->all() as $message)
     <li></li>
        @endforeach
 </ul>
</div>
@endif
<div class="container">
    <div class="row">
        <div class="col-md-10">
            <h1>Tarification tache</h1>
        <form action=" " method="post">
         

            <div class="form-group">
                <label for="technicien">Technicien</label>
                <select name="technicien_id" id="technicien" class="form-control" >

                        @foreach($techniciens as $techniciens)
                         <option value="">
                            
                         </option>
                        @endforeach
                </select>
            </div>
 ////////////
            
            <div class="form-group">
                <label for="metier">Libelle metier</label>
                <select name="metier" id="metier" class="form-
 control">

                        @foreach($metiers as $metier)
                         <option value="">
                            
                         </option>
                        @endforeach
                </select>
            </div>

            <div class="form-group">
                <label for="Tache">Libelle Tache</label>
                <select name="tache" id="Tache" class="form-control">

                        @foreach($taches as $tache)
                         <option value="">
                            
                         </option>
                        @endforeach
                </select>
            </div>
            

       //////////////
            <div class="form-group">
                <label for="">Tarif</label>
                <input type="text"  name ="Tarif" class="form-control"value="">
            </div>
            <div class="form-group">
                <input type="submit" value = "enregistrer" class="form-control btn btn-primary">
            </div>
        </form>
    </div>
</div>


<script>
    $('#metier').on('change',function(e){
        console.long(e);
        var met_id = e.target.value;

        $.get('/ajax-tac?met_id=' + met_id, function(data){
            $('#tache').empty();
            $.each(data,function(index, tacObj){
                $('#tache').append('<option value="'+tacObj.id+'">'+catObj.libelle_tache+'</option>');
            });

        });

    });
</script>

@endsection

route.php

Route::get('/tarification', 'TarificationController@index');
Route::get('/tarification/create', 'TarificationController@create');
Route::post('/tarification', 'TarificationController@store');
Route::get('/tarification/{id}/edit', 'TarificationController@edit');
Route::put('/tarification/{id}', 'TarificationController@update');
Route::delete('/tarification/{id}', 'TarificationController@destroy');

Route::get('/ajax-metier',function(){
        $met_id = Input::get('met_id');
        $taches = tache::where('metier_id','=', $met_id)->get();
        return Response::json($metiers);
});

controller

public function create()
{
    $techniciens = technicien::orderBy('id','desc')->get();
    $taches = Tache::orderBy('libelle_tache', 'asc')->get();
    $metiers = Metier::all();
    return view('tarification.create')->with('taches', $taches)->with('techniciens', $techniciens)->with('metiers', $metiers);
}

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

    $tarification ->tache_id = $request->input('tache_id');
    $tarification ->Tarif =$request->input('Tarif');
    $tarification->save();
    $tarification->techniciens()->attach($request->technicien_id);
    return redirect('home');
}



via Chebli Mohamed

Laravel Query Builder with MySQL date in between

I need to inject one WHERE clause into my existing query builder. The new WHERE condition makes me stuck on how to integrate with my existing query model.

AND (rpt_content_main.dt_added BETWEEN CURDATE() - INTERVAL $duration DAY AND CURDATE())

The existing query model

$report_items = RptContentMain::with(['UsrStudentMain'])
        ->select('rpt_content_main.*','rpt_content_type.type_name')
        ->whereIn('rpt_content_main.status_action',$pzaction)
        ->where('rpt_content_main.content_type',RPT_CONTENT_TYPE_ID_FEEDBACK)
        ->where('qst_master_main.published_status',QUESTION_STATUS_PUBLISHED)
        ->leftJoin('rpt_content_type', 'rpt_content_type.type_id', '=', 'rpt_content_main.report_type_id')
        ->leftJoin('qst_master_main','qst_master_main.question_id','=','rpt_content_main.content_id')
        ->orderBy('rpt_content_main.admin_reported','asc')
        ->orderBy('rpt_content_main.report_id','desc')
        ->paginate($per_page)
        ->appends(array(
            'q' => \Request::get('q'),
            't'   => \Request::get('t'),
            'pzaction'   => \Request::get('pzaction'),
            'duration'   => \Request::get('duration'),
        ))
    ;

How I can achieve this without break my existing query model?



via Chebli Mohamed

Laravel relationship error in migration

I am trying to make two tables relationship in laravel. But i can't understand why i'm getting error "errno: 150 "Foreign key constraint is incorrectly formed"". please check my migration code below.

items table

public function up()
{
    Schema::create('items', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('category_id')->unsigned();
        $table->string('name');
        $table->decimal('price',5,2);
        $table->integer('count_left')->default(0);
        $table->timestamps();

        $table->foreign('category_id')->references('id')->on('categories');
    });
}

categories

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



via Chebli Mohamed

Laravel: Handling unchecked checkbox with old()

When I uncheck a checkbox and validation fails I expect that checkbox remains unchecked, instead it is checked.

My checkbox:

<input type="checkbox" name="member"
   />

I tried a lot of solutions here on Stack but none works. Notice: I'm using Laravel 5.6



via Chebli Mohamed

how to make a laravel command take --env option into account

Background

I created a Laravel command that interacts with the database:

    try {
        // Get Point coordinates for each user location vote in the database 
        $result = DB::select( // blah blah

My intention is to have this command available locally, but then being able to pass it the --env=prod option so that it can interact with the production database. This works perfectly fine for example with the orangehill/iseed library where I can run a command like so:

iseed <table_name> --env=prod

side note

my prod db is RDS, hiding behind a vpc firewall. So what I did is create an ssh tunnel like so:

ssh -N -L 6666:rds.host.com:5432 user@ec2ip -i pub_file.pub"

I can easily connect to the database using command line then like so:

PGPASSWORD=password psql productiondb -U productionuser -h 127.0.0.1 -p 6666;

likewise, I have the same credentials in my .env.prod file:

APP_ENV=prod
..
DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_DATABASE=productiondb
DB_USERNAME=productionuser
DB_PASSWORD=password
DB_PORT=6666

so when i run iseed.. it reads just fine from the above and everyone is happy

problem

When I run my command on localhost like so:

$ php artisan toters:getUserVotesByLocation 63 --env=prod
Counting Votes Started @ 1519664089


  [Doctrine\DBAL\Driver\PDOException]
  SQLSTATE[08006] [7] FATAL:  role "productionuser" does not exist

it blows up! the weird part is that it kind of reads from the prod env settings (it figured it that it's using productionuser user, but it seems that the other paramters are not being read.. ie if i try to login to local db using production user i'll get the same error message:

$ psql database -U productionuser // defaults to localhost
psql: FATAL:  role "productionuser" does not exist

How do I fix this?



via Chebli Mohamed