mardi 31 décembre 2019

Searches related to search products not showing exact results in magento2

Searches related to search products not showing exact results in magento2. if I search for Endfeed Female Straight Adaptor, it's not be showing exactly that product. it will be showing all related products if, only one word is match with a search query

enter image description here



via Chebli Mohamed

How to notify the admin if the items(Multiple items) are going to expire in days later-Laravel

There are many items in the Items table and there is an expired date column in the items table. I just want to get a push notification every day before each items going expire one date before (Expire dates are different to each other and can have one expire date to multuple items). im new to laravel. Please help me.



via Chebli Mohamed

Target [App\Repositories\Setting\SettingRepositoryContract] is not instantiable while building [App\Http\Controllers\SettingsController]

How can i solve Target [App\Repositories\Setting\SettingRepositoryContract] is not instantiable while building [App\Http\Controllers\SettingsController].

Here is my controller

namespace App\Http\Controllers;
use Auth;
use Session;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Repositories\Setting\SettingRepositoryContract;
class SettingsController extends Controller
{
protected $settings;
public function __construct(
        SettingRepositoryContract $settings
    )
    {
        $this->settings = $settings;

    }

SettingRepositoryContract

namespace App\Repositories\Setting;

interface SettingRepositoryContract
{
    public function getCompanyName();

    public function updateOverall($requestData);

    public function getSetting();
}

NOTE: I am new to laravel and can't understand this error. So please help me if anyone know the answer.

Thank you



via Chebli Mohamed

Custom multi-auth guard logging & routing

I'm developing a Laravel 6 app with 4 different users(with a different table for each). For this, I am using multi auth guard and created my first guard following this tutorial online (https://pusher.com/tutorials/multiple-authentication-guards-laravel).

Here is my custom guard "student"

    'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'token',
        'provider' => 'users',
        'hash' => false,
    ],
    'student' => [
        'driver' => 'session',
        'provider' => 'students',
    ],
],

And Providers

    'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
    'students' => [
        'driver' => 'eloquent',
        'model' => App\Models\Student::class,
    ],
],

I have a custom login controller using a custom auth guard named 'student'

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Auth;
use Student;

class LoginController extends Controller
{
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
        $this->middleware('guest:student')->except('logout');
    }
    public function studentLogin(Request $request)
    {
        $this->validate($request, [
            'email'   => 'required|email',
            'password' => 'required|min:5'
        ]);

        if (Auth::guard('student')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))) {

            return redirect()->intended('admin/home')->with('smessage', 'Logged in successfully...!');
        }
        return back()->withInput($request->only('email', 'remember'));
    }...
    }

Now, Whenever I try to log in, It seems like I am logged in and redirected to the URL defined in the middleware/RedirectIfAuthenticated.php but this error pops up "Trying to get property of non-object" which is from the header where no data are on auth()->user() hence no view.blade.php is loaded.

Here are my routes:

Route::get('/', function () {
    return view('welcome');
});
Route::get('/login', 'LoginController@create')->name('login');
Route::post('login', 'LoginController@store');
Route::get('/login/student', 'LoginController@create')->name('studentlogin');
Route::post('/login/student', 'LoginController@studentLogin');

Route::get('/logout', 'LoginController@destroy')->name('logout'); 

Route::group(['prefix'=>'admin', 'namespace' => 'Dashboard', 'middleware'=> 'auth' ], function () {

    Route::get('home', 'DashboardController@display')->name('admin.home');

    Route::get('users', 'UserlistController@display')->name('admin.userlist');
    Route::post('users', 'UserlistController@store')->name('admin.create');
    Route::delete('users/{id}', 'UserlistController@destroy')->name('admin.deleteuser');

});

Route::group(['prefix'=>'student', 'namespace' => 'Students' ], function () {
    Route::get('all', 'StudentsController@display')->name('student.all');
    Route::delete('all/{id}', 'StudentsController@destroy')->name('student.delete');
    Route::post('all', 'StudentsController@store')->name('student.store');
});

Couldn't find any solutions from other related topics on StackOverflow. Please do correct me if I have any mistakes somewhere or let me know if you want to inspect any other files for the code.

Thanks in advance.



via Chebli Mohamed

Laravel - regex route match everything but not exactly one or more word

I make a route like

Route::get('/{url1}', function ($url1) {
    return ' url1: '.$url1;
})
->where('url1', '^(?!(string1|string2)$)');

and access url like:
- domain/abc not found => incorrect ??
- domain/string1 not found => correct

and more, when i do with

Route::get('/{url1}/{url2}', function ($url1) {
    return ' url1: '.$url1;
})
->where('url1', '^(?!(string1|string2)$)');

and access url like:
- domain/abc/abc not found => incorrect ???
- domain/string1/abc not found => correct

How to fix that thank



via Chebli Mohamed

Laravel Pusher uses old apikey only in aws -> how can I clear/ change it?

I have an angular & laravel app that uses pusher. I changed the apiKey, secret etc in the .env in laravel. It works well on local but when I try on AWS EC2 the credentials are still the old ones:

$config = config('broadcasting.connections.pusher');
   dd($config) // gives old credentials only in staging/aws

I tried all the clearing (cache:clear, route:clear etc), in the local and in the AWS-cli and it gave me the notification that everything was ok ('cleared!').

Is there a way to clear or set the .env through the AWS dashboard?

PS - the old credentials are no where to be found in the client & back side. Unless laravel itself is still storing the old credentials?



via Chebli Mohamed

Laravel correct way to name and define routes?

Example 1:

Route::get('/', 'API\PostController@index')->name(‘post.index’);

Example 2:

Route::get('/', [PostController::class, 'index'])->name(‘post.index’);

In this example we need to use the following use statement at the top of the route file:

use App\Http\Controllers\API\PostController;

The second example makes it easy to navigate across the controllers from the route file with a cmd + click but compared to better performance which is the best ?

Is it must to define named routes when using the laravel only as a API, can it add more overhead to overall performance ?



via Chebli Mohamed

Laravel validation for exists except zero not nullable

In categories table I have the following columns id, parent_id, title

Now, parent_id is the parent category for sub-category, but for the root/primary categories parent_id is 0 because they have no parent!

<?php
'parent_id'=>'required|exists:categories,id|nullable' 
// wont work, because parent_id = 0

I used also [sometimes] with no luck!



via Chebli Mohamed

Testing Middleware in Laravel with PHPUnit?

Route::group(['middleware' => ['web']], function () { Route::get('/contact', 'TicketsController@create'); Route::post('/contact', 'TicketsController@store');});



via Chebli Mohamed

Reassign with new value to global variable Laravel PHP

I have a below kind of snippet in my Laravel project where I'm trying to re-assign value to the global variable $ischecked and $isselectedValue in a method ValidateValue() and I'm trying to access the same variable with the updated values in second method called useThoseValues() but I couldn't get the updated value. Kindly help me on this

class testController extends controller {

  public $isChecked = false;
  public $isSelectedValue = 0;

  public function ValidateValue(Request $req)
  {
    $isChecked = $req->checked;
    $isSelectedValue = $req->value;
  }

  public function UsethoseValues()
  {
    if ($isChecked) { // this variable values is not getting updated
    }
  }
}


via Chebli Mohamed

Is there a solution for Missing required parameters for [Route:....?

I have searched everywhere and no one has provided a proper solution or it is left unanswered. Could someone please help me with this error? I have been struggling for days now. enter image description here

Missing required parameters for [Route: helper.update] [URI: helper/{id}]. (View: D:\Training\LaravelProjects\helps\resources\views\helper\edit.blade.php)

I have followed the documentation and still i can't figure out what is wrong. This is my code.

Web.php

Route::group(['prefix' => 'helper'], function (){
 Route::get('/create', [
    'uses' => 'HelperController@create',
    'as' => 'helper.create'
 ]);

 Route::get('/{id}/edit', [
    'uses' => 'HelperController@edit',
    'as' => 'helper.edit'
 ]);

 Route::get('/{id}', [
    'uses' => 'HelperController@show',
    'as' => 'helper.show'
 ]);

 Route::post('/', [
    'uses' => 'HelperController@store',
    'as' => 'helper.store'
 ]);

 Route::put('/{id}', [
    'uses' => 'HelperController@update',
    'as' => 'helper.update'
 ]);

 Route::delete('/{id}', [
    'uses' => 'HelperController@destroy',
    'as' => 'helper.destroy'
 ]);
});

HelperController.php

public function edit($id)
{
    $helper = Helper::find($id);
    return view('helper.edit', compact('helper'));
}

index.blade.php

<tbody>
                @foreach($helpers as $helper)
                <tr>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td>
                        <a href="" class="edit">
                            <i class="fas fa-pencil-alt" title="Edit" style="font-size: 16px"></i>
                        </a>
                        <a href="#deleteEmployeeModal" class="delete" data-toggle="modal" data-widget="">
                            <i class="fas fa-trash" title="Delete" style="font-size: 16px"></i>
                        </a>
                    </td>
                </tr>
                @endforeach

All I want is to open the edit.blade.php file once I click edit link. The delete part is incomplete and please ignore that. Also, the id is being passed as a parameter but stil says it's missing. Check this image enter image description here



via Chebli Mohamed

Can Docker container run two projects of different version of PHP on same AWS ec2 server?

My old Project was in PHP 5.6 & Laravel 5.4 deployed on AWS ec2 server, Now I am deploying new project on the same server but since we cant keep two different project with different versions of PHP on same AWS ec2 instance. Can we solve this issue by docker container?



via Chebli Mohamed

Laravel Redis php_network_getaddresses: getaddrinfo failed: Name or service not known [tcp://redis:6379]

Server throwing below error may be on heavy site traffic or loss of redis connection. But unable to found the cause of this error that can help to resolve. So any help regarding this will be helpful.

Server : Digital Ocean
Frontend : React JS
Backend : laravel (5.8)
Used spiritix/lada-cache library for mysql cashing to manage large amount of data.
Application is running on Docker containers.

production.ERROR: php_network_getaddresses: getaddrinfo failed: Name or service not known [tcp://redis:6379] {"exception":"[object] (Predis\Connection\ConnectionException(code: 0): php_network_getaddresses: getaddrinfo failed: Name or service not known [tcp://redis:6379] at /var/www/vendor/predis/predis/src/Connection/AbstractConnection.php:155)

This error will stops the server as well.



via Chebli Mohamed

OrderBy Coupons based on expiration status Laravel

I need to display list of coupons and order it based on created_at date and expiration status.

The columns of my Coupons table

id
name
price
expired_at
created_at
status

My laravel query

$coupons= Coupon::where('status', 2)->orderBy('created_at', 'DESC')->orderBy( First I will need to compare expired_at with today date here)->get();

The problem is I dont know how to orderBy coupon_status, I want to display all expired coupons at bottom of the list and on-going coupons at top of the list and also orderBy created_at (the newest and on-going coupons is at the top of the list)

Any Idea how to achieve this result?



via Chebli Mohamed

Laravel - Auth::user data return null except Login Controller

I am creating user authentication using a custom table. In my login controller authentication is working fine and redirected to dashboard. But when I am going to create another url using a new controller, user auth data not showing for that controller. Here is my code:

web.php:

<!---Routes for login and dashboard-->

Route::get('/login','CustomLogin@index');
Route::post('/login','CustomLogin@checklogin');
Route::get('/','CustomLogin@SuccessLogin');
Route::get('/logout','CustomLogin@logout');

<!---Routes for other controller where user auth not working-->

Route::get('/add-creditor', 'AddCreditor@index');

CustomLogin.php (controller):

    <?php

namespace App\Http\Controllers;

use App\library\My_functions;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\User;
use Illuminate\Support\Facades\Auth;
use Redirect;
use View;
use Session;
use Cookie;

class CustomLogin extends Controller
{
    public function __construct()
    {
        $this->_myFun = new My_functions;
    }

    public function index()
    {
        if(!Auth::check()) {
            return view('CustomLogin.CustomLogin');
        }
        else{
            Redirect::to(SITE_URL)->send();
        }
    }

    public function username()
    {
        return 'user_name';
    }

    function checklogin(Request $request)
    {
        $this->validate($request, [
           'input-username'     =>      'required',
           'input-password'     =>      'required'
        ]);

        $user_data = array(
            'user_name'  => $request->get('input-username'),
            'password' => $request->get('input-password')
        );

        if(Auth::attempt($user_data)){
            return redirect('/');
        }
        else
        {
            return back()->with('error','Wrong Login Details');
        }
    }

    function SuccessLogin(){
        if (!$this->_myFun->DoLogIn()) {
            Redirect::to(SITE_URL.'login')->send();
        }
        else {
            $data=array();
            return View::make('include.dashboard',$data);
        }
    }

    function logout(Request $request){
        Auth::logout();
        return redirect('/login');
    }

}

Function DoLogIn() (app/library)

<?php namespace App\library {
use Illuminate\Routing\Controller as BaseController;
use App\library\CreateCrmGuid; // Get custom function
use App\library\FunctionForContact; // Get custom function
use Illuminate\Http\Request;
use Session;
use DB;
use Hash;
use Auth;
use App\User;
class My_functions{

    public function DoLogIn()
    {
        //dd(Auth::user()); /*returns data if run from Login controller but null from Add Creditor controller*/
        if(Auth::check())
        {
            $user_id = Auth::user()->id;
            define('authenticated_user_id' ,$user_id);
            return true;
        }
        else
        {
            return false;
        }
    }
}

AddCreditor Controller

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Cookie;
use Config;
use App\library\my_functions; // Get custom function
use Redirect;
use DB;
use Session;

class AddCreditor extends Controller
{
    protected $_myFun;

    function __construct(){
        dd(Auth::user());  // this returns null
        $this->_myFun = new My_functions;
        if (!$this->_myFun->DoLogIn()) {
            Redirect::to(SITE_URL.'login')->send();
        }
    }
}


via Chebli Mohamed

lundi 30 décembre 2019

Laravel- Show errors on the login page when login credentials are wrong

I am new to Laravel. I am designing an login page and I want to show the errors on login page itself when the login credentials are wrong. I haven't done anything in controller. I am using the inbuilt Laravel function-Auth.



via Chebli Mohamed

Laravel redirect to home after login [closed]

I have a problem here, I made a multi-level login, there are 3 levels here admin, Santri, Management when the admin and Management log in they redirect to where they should be but why when santri login redirect to home

  protected function authenticated(Request $request, $user)
{

    if ($user->level == 'admin') {
        return redirect('/admin');
    } 
    if ($user->level == 'santri') {
        return redirect('/santri');
    } 
    if ($user->level == 'pengurus') {
        return redirect('/pengurus');
    } 
}


via Chebli Mohamed

Multiple files view in email template laravel

I have an array of image path to attach with email. How can i view them in a email template?

SendMailController:

  $files = collect(json_decode($img_files))->map(function ($file) {
    return public_path('uploads' . DIRECTORY_SEPARATOR . $file->name);
  })->toArray();

  Mail::to($customer_email)->send(new SendMail($customer_firstname, $pathToFile), function($message){
        foreach ($files as $filePath) {
            $message->attach($filePath);
        }
      }
  );

In my email template:

<img src="" style="width:600px;height:335px">

But this gives, Undefined variable: filePath error. How can i this



via Chebli Mohamed

How to destroy session when clicks on browser's back button

I am flashing a success message using session->flash() method in laravel. But when user clicks back button the message comes up again. How to fix this. My code for showing message is -

@if(Session::get('success') )
    <script>
        swal({
            text: "",
            button: localMsg.ok,

        }).then((isConfirm) => {
        });
    </script>
    @elseif(Session::get('error'))
    <script>
        swal({
            text: "",
            button: localMsg.ok,

        }).then((isConfirm) => {
        });

    </script>
@endif


via Chebli Mohamed

How to count revisited customer ( more than 1 time) in laravel using query builder?

I need to count revisited customer in one month. It means need to count customer_id has more than one entry in table within a month.

My query is showing only the total customer.

$count_customer_current_month = DB::table("customer_entry")->whereRaw('MONTH(date) = ?', 
                                [$currentMonth])->count();


via Chebli Mohamed

the required field change to red

help me on required field that suppose to change color when empty like this:

enter image description here

the dropdown on course_id and grade_id should change to red when the required field appear after the submit the form.

this is the form i use to create the form for past education.

form_modal.blade.php:


    <div class="form-group required">
        <label class="col-lg-2 control-label"></label>
        <div class="col-lg-4">
            {!! Form::dropdown('institution_id', $institution, @$pasteducationinfo['institution_id'],'class="select2-form institution_id"') !!}
        </div>
    </div>
    <div id="institution" class="form-group hide">
        <label class="col-lg-2 control-label"></label>
        <div class="col-lg-4">
            <input type="text" name="institution_name" class="form-control" value="" placeholder="SMK Cyberjaya">
        </div>
    </div>
    @if(!empty($edulevelinfo['is_course_able']))
    <div class="table-responsive repeater">
        <table id="courseassessmentnew-table" class="table table-striped b-t b-b" data-repeater-list="pasteducation">
            <thead>
                <th>{!! msg('lbl_course') !!}</th>
                <th>{!! msg('lbl_grade') !!}</th>
                <th></th>
            </thead>
            <tbody>
            @if(!empty($pasteducationdetailinfo))
                @foreach($pasteducationdetailinfo as $detailinfo)
                    @if (!empty($detailinfo->educationCourse->is_mandatory))
                        <tr>
                            <td>
                                {!! $educourseselection[$detailinfo['course_id']] !!}
                                <input type="hidden" name="course_id[]" value="">
                            </td>
                            <td>
                                {!! Form::dropdown('grade_id[]', $gradeselection, $detailinfo['grade_id'],'class="select2-form"') !!}
                            </td>
                            <td></td>
                        </tr>
                    @else
                        <tr data-repeater-item>
                            <td>
                                {!! Form::dropdown('course_id', $mandeducationcourse, $detailinfo['course_id'],'class="select2-form past-education-course"') !!}
                            </td>
                            <td>
                                {!! Form::dropdown('grade_id', $gradeselection, $detailinfo['grade_id'],'class="select2-form"') !!}
                            </td>
                            <td>
                                <span data-repeater-delete="" class="btn btn-danger">
                                    <i class="glyphicon glyphicon-remove" ></i>
                                </span>
                            </td>
                        </tr>
                    @endif
                @endforeach
                <tr data-repeater-item>
                    <td>
                        {!! Form::dropdown('course_id', $educourse, '','class="select2-form past-education-course" required') !!}
                    </td>
                    <td>
                        {!! Form::dropdown('grade_id', $gradeselection, '','class="select2-form" required') !!}
                    </td>
                    <td>
                        <span data-repeater-delete="" class="btn btn-danger">
                            <i class="glyphicon glyphicon-remove" ></i>
                        </span>
                    </td>
                </tr>
            @else <?php //display field for new application ?>
                @if ($mandeducourseselection->count() > 0)
                    @foreach ($mandeducourseselection as $item)
                    <tr>
                        <td>
                        {!! $item->name !!}
                            <input type="hidden" name="course_id[]" value="">
                        </td>
                        <td>
                            {!! Form::dropdown('grade_id[]', $gradeselection, '','class="select2-form" required') !!}
                        </td>
                    </tr>
                    @endforeach
                @endif
                <tr data-repeater-item>
                    <td>
                        {!! Form::dropdown('course_id', $educourseselection, '','class="select2-form past-education-course" required') !!}
                    </td>
                    <td>
                        {!! Form::dropdown('grade_id', $gradeselection, '','class="select2-form" required') !!}
                    </td>
                    <td>
                        <span class="btn btn-danger" onClick="removerow(this)">
                            <i class="glyphicon glyphicon-remove" ></i>
                        </span>
                    </td>
                </tr>
            @endif
            </tbody>
            <tr>
                <td colspan="2"></td>
                <td>
                    <span data-repeater-create="" class="btn btn-success btn-md">
                        <i class="glyphicon glyphicon-plus"></i>
                    </span>
                </td>
            </tr>
        </table>
    </div>
    @endif
</div>
<input type="hidden" name="student_id" value="" />
<input type="hidden" name="past_education_id" value="" />
<input type="hidden" name="education_level_id" value="" />
<!-- /content -->

{!! JsValidator::formRequest('App\Http\Requests\Student\PastEducationRequest', '#form-education' ); !!}

the next file is a request file that i use to do the checking of mandatory field. pasteducationrequest.php:

<?php

namespace App\Http\Requests\Student;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Request;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'education_level_id'         => 'required',
            'institution_id'             => 'required',
            'pasteducation.0'            => 'required|sometimes',
            'pasteducation.1'            => 'required|sometimes',
            'pasteducation.2'            => 'required|sometimes',
            'pasteducation.3'            => 'required|sometimes',
            'pasteducation.4'            => 'required|sometimes',
            'pasteducation.5'            => 'required|sometimes',
            'pasteducation.6'            => 'required|sometimes',
            'pasteducation.7'            => 'required|sometimes',
            'pasteducation.8'            => 'required|sometimes',
            'pasteducation.9'            => 'required|sometimes',
            'pasteducation.10'           => 'required|sometimes',
            'pasteducation.11'           => 'required|sometimes',
            'pasteducation.12'           => 'required|sometimes',
            'pasteducation.13'           => 'required|sometimes',
            'pasteducation.14'           => 'required|sometimes',
            'pasteducation.15'           => 'required|sometimes',
            'pasteducation.16'           => 'required|sometimes',
            'pasteducation.17'           => 'required|sometimes',
            'pasteducation.18'           => 'required|sometimes',
            'pasteducation.19'           => 'required|sometimes',
            'pasteducation.0[course_id]' => 'required',
        ];
    }
}



via Chebli Mohamed

Isset check on Array - Blade Laravel 5.8

If I do

I got

array:7 [▼
  "created_at" => "2019-12-30 17:31:55.728307+00:00"
  "fail_cnt" => 123
  "updated_at" => "2019-12-30 17:31:55.728307+00:00"
]

Hints: It is an array, not an object.

I'm trying to use the isset check on an array

<input required type="number" name="slaac" class="form-control form-control-sm"  placeholder="1000" value="">

I kept getting

What did I do wrong ?



via Chebli Mohamed

laravel not finding css and js

how are you ?

i upload my project to share hosting but it not downloading the css and js files

the .htaccess file that in public folder

<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>

and this is the .htaccess file that i made in project folder

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_URI} !^/public/ 

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f



RewriteRule ^(.*)$ /public/$1 
#RewriteRule ^ index.php [L]
RewriteRule ^(/)?$ public/index.php [L] 
</IfModule>

and when i lunch the inspect i saw this 404 pages

enter image description here



via Chebli Mohamed

Laravel - Get list of files in directory, no such file or directory

I am trying to get a list of all the files in the directory resources/layouts/layouts/ where all my layouts are located. In my controller I can do something like this:

        $dir = "../resources/views/layouts/layouts";
        $list = scandir($dir,1);
        $newlist = array_splice($list, -2);

        foreach($list as $item) {
            $dir = "../resources/views/layouts/layouts/";
            $filepath = $dir . $item;
            $content = file_get_contents($filepath);
        }

And this just returns a list of the names and content of the files in that directory like no problem. But when I try to do the same in my LayoutSeeder file and try to populate the database with the data I get the error

failed to open dir: No such file or directory on the line $list = scandir($dir,1);

Code

public function run()
    {
        $dir = "../resources/views/layouts/layouts";
        $list = scandir($dir,1);
        $newlist = array_splice($list, -2);

        foreach($list as $item) {
            $dir = "../resources/views/layouts/layouts/";
            $filepath = $dir . $item;
            $content = file_get_contents($filepath);

            DB::table('layouts')->insert([
                'name' => strtok($item, '.'),
                'content' => $content,
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
            ]);
        }
    }

Why does it work in my controller but not in my seeder? I'm only one level away from the base directory so ../ should do the trick like it does in the controller. But it does not work



via Chebli Mohamed

how to marge 2 array based on value?

I have 2 arrays, in this case, I want to combine the two arrays into one. Here I have 2 arrays namely remarks and remark_asset

here are the array of remarks

[
  {
    "id": 5,
    "type": "Text",
    "name": "Text",
    "label": "Txt L",
    "description": "Txt D",
    "filter_logic": null,
    "default": "Txt Def",
    "weight": "12",
    "required": "true",
    "created_at": "2019-12-10 18:20:37",
    "updated_at": "2019-12-10 18:20:37"
  },
  {
    "id": 6,
    "type": "Date",
    "name": "Date",
    "label": "Date Label",
    "description": "Date DEsc",
    "filter_logic": null,
    "default": "2019-12-10",
    "weight": "12",
    "required": "false",
    "created_at": "2019-12-10 18:30:29",
    "updated_at": "2019-12-10 18:30:29"
  },
  {
    "id": 7,
    "type": "Checkbox",
    "name": "Kotaro",
    "label": "Cex",
    "description": "cex desc",
    "filter_logic": null,
    "default": "true",
    "weight": "11",
    "required": "false",
    "created_at": "2019-12-10 18:32:13",
    "updated_at": "2019-12-10 18:32:13"
  },
  {
    "id": 13,
    "type": "List",
    "name": null,
    "label": "Label",
    "description": "Desc",
    "filter_logic": null,
    "default": "1,2,3,4",
    "weight": null,
    "required": "false",
    "created_at": "2019-12-30 01:46:44",
    "updated_at": "2019-12-30 01:46:44"
  }
]

and this is an array of remark assets

[
  [
    {
      "id": 210,
      "asset_id": 94092,
      "remark_id": 5,
      "value": "Txt Def",
      "created_at": "2019-12-13 08:55:41",
      "updated_at": "2019-12-13 08:55:41"
    },
    {
      "id": 211,
      "asset_id": 94092,
      "remark_id": 6,
      "value": "2019-12-10",
      "created_at": "2019-12-13 08:55:41",
      "updated_at": "2019-12-13 08:55:41"
    },
    {
      "id": 212,
      "asset_id": 94092,
      "remark_id": 7,
      "value": "true",
      "created_at": "2019-12-13 08:55:41",
      "updated_at": "2019-12-13 08:55:41"
    }
  ],
  [
    {
      "id": 213,
      "asset_id": 94093,
      "remark_id": 5,
      "value": "Txt Def",
      "created_at": "2019-12-13 09:00:16",
      "updated_at": "2019-12-13 09:00:16"
    },
    {
      "id": 214,
      "asset_id": 94093,
      "remark_id": 6,
      "value": "2019-12-10",
      "created_at": "2019-12-13 09:00:16",
      "updated_at": "2019-12-13 09:00:16"
    },
    {
      "id": 215,
      "asset_id": 94093,
      "remark_id": 7,
      "value": "true",
      "created_at": "2019-12-13 09:00:16",
      "updated_at": "2019-12-13 09:00:16"
    }
  ]
]

and my expectation value is like this

[
 {
    "Txt L": "Txt Def",
    "Date Label": "2019-12-10",
    "Cex": "true",
    "Label": null
  }
]

so I will explain about my question, so in the array that I want the key of the array is the label of the remax array, then the value of the key is the data of the value contained in the said asset, so the key displayed will be dynamic, here I have take out each array, now how do I make it possible to join the two arrays? So the value part must match the id remark, for example "Txt L": the value is data that has the same id as "Txt L":

and this is my code :

$getData = $data->get()->take(10);
            $remark = Remark::all();
            $remarkAsset = RemarkAsset::all();

/* ------------------------------ REMARK ASSET ------------------------------ */
            $resultRemarkAsset = array();
            foreach ($remarkAsset as $dataRemark) {
                $resultRemarkAsset[$dataRemark['asset_id']][] = $dataRemark;
            }
            $remarkAssetValue = array_values($resultRemarkAsset); //result


via Chebli Mohamed

How i make a shown footer at bottom page on laravel?

I make a footer. but to see the footer, i need to scroll it down. I want too see the footer without scrolling the page



via Chebli Mohamed

Pass image in yield section in laravel

For the <title> I've followed this SO answer This is working perfectly for part but the image is not working

Laravel dynamic page title in navbar-brand

But, Here when I try to make an image dynamic instead of title it's giving me a text instead of an image.

For instance,

header.blade.php

@yield('image')

In another blade, I called image as in section

@section('image', '<img src="http://localhost/appname/public/front/images/heading.png">')

Every page has a dynamic logo so I want to put logo dynamic the same like we're doing in the title.

But the result I'm getting is enter image description here

<img src="http://localhost/appname/public/front/images/heading.png">


via Chebli Mohamed

How to make multi-level routes - Laravel

I try to make route like

  1. Post URL
    domain/{...dynamic-category...}/post-slug
    with {...dynamic-category...} like sub-cate/sub1-cate...

=> My route: Route::get('/{cate}/{post}', ['as' => 'post', 'uses' => 'PostController@index'] );
  1. Category Paging
    domain/{...dynamic-category...}/page/{page-number}

=> My route: Route::get('/{cate}/page/{page-number}', ['as' => 'cate', 'uses' => 'CateController@index'] );

But my route is a simple level. How to do that thank.



via Chebli Mohamed

How to add new key value pair in response of groupBy in laravel?

I have a order table where it contains id,order_id,user_id,etc

I applied groupBy() over order Eloquent like below:

`$orders = DB::table('orders')->whereUserId($userId)->groupBy('order_id')->get();`

So, here I am getting response like:

Collection {#547 ▼
  #items: array:1 [▼
    "d0b942a572941b90f385" => Collection {#535 ▼
      #items: array:4 [▼
        0 => Order {#561 ▶}
        1 => Order {#562 ▶}
        2 => Order {#563 ▶}
        3 => Order {#564 ▶}
      ]
    }
  ]
}

Now I am applying foreach loop over here so that I can add new kew value pair to particular above 4 array but Its now adding this new key value pair. I done the code like below:

foreach($orders as $order){

   $order['ee']='test';
 }

I am not getting where I am getting it wrong, because I check it line by line in foreach loop then it add it properly but while I check outside of loop, its now showing me this new key value pair



via Chebli Mohamed

Carbon date Difference method giving wrong date difference in Laravel 5.7 [closed]

I am getting wrong Date difference between two dates using Carbon in Laravel 5.7.

here this image is showing you Date of sdate value and edate value

enter image description here

my code is

$date = Carbon::parse($sdate);
$now = Carbon::parse($eDate);
$diff = $date->diffInDays($now);
  return ["sdate"=>$sdate,
          "eDate"=>$eDate,
          "total" => $diff, 
          "holidays" => $holidayDayCount,
          "classes" => $diff - count($leaveDayArr),'sunday'=>$sundayArr ,'offDate'=>$offDay
        ];

After this I am getting in API response.

enter image description here

it is showing me 29 but it should be 30.



via Chebli Mohamed

Laravel public folder redirects to root domain name

So basically here's my base directory on my server

/var/www/html/server

Where my laravel project is inside the server folder

If i access the site at https://www.sympies.net/server/public/ it redirects to https://www.sympies.net/public . I dont understand why. I removed the .htaccess inside the public folder already

Here's my .htaccess code on laravel root folder

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
<IfModule mime_module>
  AddType application/x-httpd-ea-php71 .php .php7 .phtml
</IfModule>

This one is for my

000-default-le-ssl.conf

<IfModule mod_ssl.c>
<VirtualHost *:443>
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combin
ServerName www.sympies.net
SSLCertificateFile /etc/letsencrypt/live/www.sympies.net/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/www.sympies.net/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>

Yesterday , the public folder works but only when i access it via http not https, and when i access it via https , it redirects again back to its root https://www.sympies.net/public



via Chebli Mohamed

Here my code to insert multiple records in database on laravel. So, it doesn't work? anyone help me?

i want insert multiple records in table at once submit into database using eloquent laravel, so i have tried hardly.

my code on controller

 $x = $request->all();
 $datas = DataAnak::create($x)->id_anak;

            if($datas != 0) {
                foreach ($datas as $key => $value) {
                    $rows = array(
                        'nama' => $request->nama_anak[$key],
                        'jenis_kelamin' => $request->gender_anak[$key],
                        'tempat_tgl_lahir' => $request->tmt[$key],
                        'tgl_baptis' => $request->baptis_anak[$key],
                        'tgl_sidi' => $request->sidi_anak[$key]
                    );
                    DataAnak::insert($rows);
                }
            }

my code on blade page

 <tr>
         <td><input type="text" class="form-control" name="nama_anak[]"></td>
         <td><input type="text" class="form-control" name="gender_anak[]"></td>
         <td><input type="text" class="form-control" name="tmt[]"></td>
         <td><input type="text" class="form-control" name="baptis_anak[]"></td>
         <td><input type="text" class="form-control" name="sidi_anak[]"></td>
         <td class="text-center"><button type="button" class="btn btn-danger row-del"><i class="fas            fa-times"></i></button></td>
    </tr>


via Chebli Mohamed

dimanche 29 décembre 2019

How to get sum along with this Laravel Eloquent query

Database Structure:
Table: sales_payments
columns: id, payer_id, payment_status, amount , ...

Please see this eloquent query. it's working fine but now i need the sum of amount key along with this given eloquent query and where conditions.

    $query =  SalesPayment::with(['abc.xyz'])

        ->whereHas('abc.xyz', function ($query) use ($options) {
            $query->where('xyz_id',$options['xyz_id']);
        });

    $query->where(['key3' => key3(), 'payment_status' => PAYMENT_STATUS_SUCCESS]);
    $query->orderBy('created_at', 'desc');
    return $query->paginate(config('constants.PAGE_LIMIT'));

Possible Solution

Just put a select as mentioned below

$query =  SalesPayment::select('*', \DB::raw('SUM(amount) AS total_sale_amount')->with ....

I have tested this solution it's working fine.

Please let me know if there is a better solution than this. And I'm looking for some other solutions Also.

Edit: But there is one problem with this solution that it returning me only one record when i put aggregate function (sum) in select otherwise it was returning more than one records.



via Chebli Mohamed

Container.php 729: Class translator does not exists

1) Container.php 729: Class translator does not exists

Steps to reproduce:-
- In your composer.json add "mews/captcha": "2.2"
- Find the providers key in config/app.php and register the Captcha Service Provider

'providers' => [
        // ...
        'Mews\Captcha\CaptchaServiceProvider',
    ]

Upon saving the file, I receive Container.php 729: Class translator does not exists. And if I comment out the provider the error goes away.


2) If I register the CaptchaServiceProvider in the providers and run any artisan command, I receive array_merge(): Argument #2 is not an array

$ php artisan config:clear

In ServiceProvider.php line 59:

  array_merge(): Argument #2 is not an array  

I tried changing the mews/captcha version but no luck there. Feedback would be highly appreciated.



via Chebli Mohamed

How to change timestamps in laravel?

i want to change the timestamp to current time but it doesn't work. What should i do?

 $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
            $table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));


via Chebli Mohamed

How can I improve the TTFB for Laravel project?

I engaged with a Laravel AMP project which uses Laravel 5.6. The project is launched in the server (apache http server) and running (also running other 4 sites on the same server). The server has:

  • Processor : Intel(R) Xeon(R) CPU E3-1220 v3 @ 3.10GHz
  • Memory : 16226420 kB (16GB)

When I checked the page with Webpagetest, it shows F grade for First Byte Time.

How can I improve the performance of First Time Byte to grade "A"?

Performance test result

Information about First Byte Time

enter image description here

WaterFall

enter image description here

And I have the following content in the .htaccess file which in the public_html folder.

# Apache configuration file
# httpd.apache.org/docs/2.2/mod/quickreference.html

# Note .htaccess files are an overhead, this logic should be in your Apache
# config if possible: httpd.apache.org/docs/2.2/howto/htaccess.html

# Techniques in here adapted from all over, including:
#   Kroc Camen: camendesign.com/.htaccess
#   perishablepress.com/press/2006/01/10/stupid-htaccess-tricks/
#   Sample .htaccess file of CMS MODx: modxcms.com


# ----------------------------------------------------------------------
# Better website experience for IE users
# ----------------------------------------------------------------------

# Force the latest IE version, in various cases when it may fall back to IE7 mode
#  github.com/rails/rails/commit/123eb25#commitcomment-118920

RewriteEngine on

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
RewriteCond %{ENV:HTTPS} !on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


#RewriteCond %{HTTPS}s ^on(s)|
#RewriteRule ^(.*)$ http%1://www.%{HTTP_HOST}/$1 [R=301,L]




<IfModule mod_headers.c>
  Header set X-UA-Compatible "IE=Edge"
  # mod_headers can't match by content-type, but we don't want to send this header on *everything*...
  <FilesMatch "\.(appcache|crx|css|eot|gif|htc|ico|jpe?g|js|m4a|m4v|manifest|mp4|oex|oga|ogg|ogv|otf|pdf|png|safariextz|svg|svgz|ttf|vcf|webm|webp|woff|woff2|xml|xpi)$">
    Header unset X-UA-Compatible
  </FilesMatch>
</IfModule>


# ----------------------------------------------------------------------
# Cross-domain AJAX requests
# ----------------------------------------------------------------------

# Serve cross-domain Ajax requests, disabled by default.
# enable-cors.org
# code.google.com/p/html5security/wiki/CrossOriginRequestSecurity

#  <IfModule mod_headers.c>
#    Header set Access-Control-Allow-Origin "*"
#  </IfModule>


# ----------------------------------------------------------------------
# CORS-enabled images (@crossorigin)
# ----------------------------------------------------------------------

# Send CORS headers if browsers request them; enabled by default for images.
# developer.mozilla.org/en/CORS_Enabled_Image
# blog.chromium.org/2011/07/using-cross-domain-images-in-webgl-and.html
# hacks.mozilla.org/2011/11/using-cors-to-load-webgl-textures-from-cross-domain-images/
# wiki.mozilla.org/Security/Reviews/crossoriginAttribute

<IfModule mod_setenvif.c>
  <IfModule mod_headers.c>
    # mod_headers, y u no match by Content-Type?!
    <FilesMatch "\.(gif|ico|jpe?g|png|svg|svgz|webp)$">
      SetEnvIf Origin ":" IS_CORS
      Header set Access-Control-Allow-Origin "*" env=IS_CORS
    </FilesMatch>
  </IfModule>
</IfModule>


# ----------------------------------------------------------------------
# Webfont access
# ----------------------------------------------------------------------

# Allow access from all domains for webfonts.
# Alternatively you could only whitelist your
# subdomains like "subdomain.example.com".

<IfModule mod_headers.c>
  <FilesMatch "\.(eot|font.css|otf|ttc|ttf|woff|woff2)$">
    Header set Access-Control-Allow-Origin "*"
  </FilesMatch>
</IfModule>


# ----------------------------------------------------------------------
# Proper MIME type for all files
# ----------------------------------------------------------------------

# JavaScript
#   Normalize to standard type (it's sniffed in IE anyways)
#   tools.ietf.org/html/rfc4329#section-7.2
AddType application/javascript         js jsonp
AddType application/json               json

# Audio
AddType audio/mp4                      m4a f4a f4b
AddType audio/ogg                      oga ogg

# Video
AddType video/mp4                      mp4 m4v f4v f4p
AddType video/ogg                      ogv
AddType video/webm                     webm
AddType video/x-flv                    flv

# SVG
#   Required for svg webfonts on iPad
#   twitter.com/FontSquirrel/status/14855840545
AddType     image/svg+xml              svg svgz
AddEncoding gzip                       svgz

# Webfonts
AddType application/vnd.ms-fontobject  eot
AddType application/x-font-ttf         ttf ttc
AddType application/x-font-woff        woff
AddType application/x-font-woff        woff2
AddType font/opentype                  otf

# Assorted types
AddType application/octet-stream            safariextz
AddType application/x-chrome-extension      crx
AddType application/x-opera-extension       oex
AddType application/x-shockwave-flash       swf
AddType application/x-web-app-manifest+json webapp
AddType application/x-xpinstall             xpi
AddType application/xml                     rss atom xml rdf
AddType image/webp                          webp
AddType image/x-icon                        ico
AddType text/cache-manifest                 appcache manifest
AddType text/vtt                            vtt
AddType text/x-component                    htc
AddType text/x-vcard                        vcf


# ----------------------------------------------------------------------
# Allow concatenation from within specific js and css files
# ----------------------------------------------------------------------

# e.g. Inside of script.combined.js you could have
#   <!--#include file="libs/jquery-1.5.0.min.js" -->
#   <!--#include file="plugins/jquery.idletimer.js" -->
# and they would be included into this single file.

# This is not in use in the boilerplate as it stands. You may
# choose to use this technique if you do not have a build process.

#<FilesMatch "\.combined\.js$">
#  Options +Includes
#  AddOutputFilterByType INCLUDES application/javascript application/json
#  SetOutputFilter INCLUDES
#</FilesMatch>

#<FilesMatch "\.combined\.css$">
#  Options +Includes
#  AddOutputFilterByType INCLUDES text/css
#  SetOutputFilter INCLUDES
#</FilesMatch>


# ----------------------------------------------------------------------
# Gzip compression
# ----------------------------------------------------------------------

<IfModule mod_deflate.c>

  # Force deflate for mangled headers developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/
  <IfModule mod_setenvif.c>
    <IfModule mod_headers.c>
      SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
      RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
    </IfModule>
  </IfModule>

  # Compress all output labeled with one of the following MIME-types
  # (for Apache versions below 2.3.7, you don't need to enable `mod_filter`
  # and can remove the `<IfModule mod_filter.c>` and `</IfModule>` lines as
  # `AddOutputFilterByType` is still in the core directives)
  <IfModule mod_filter.c>
    AddOutputFilterByType DEFLATE application/atom+xml \
                                  application/javascript \
                                  application/json \
                                  application/rss+xml \
                                  application/vnd.ms-fontobject \
                                  application/x-font-ttf \
                                  application/x-font-truetype
                                  application/xhtml+xml \
                                  application/xml \
                                  font/opentype \
                                  image/svg+xml \
                                  image/x-icon \
                                  text/css \
                                  text/html \
                                  text/plain \
                                  text/x-component \
                                  text/xml
  </IfModule>

</IfModule>

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

# ----------------------------------------------------------------------
# Expires headers (for better cache control)
# ----------------------------------------------------------------------

# These are pretty far-future expires headers.
# They assume you control versioning with filename-based cache busting
# Additionally, consider that outdated proxies may miscache
#   www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/

# If you don't use filenames to version, lower the CSS and JS to something like
# "access plus 1 week".

<IfModule mod_expires.c>
  ExpiresActive on

# Perhaps better to whitelist expires rules? Perhaps.
  ExpiresDefault                          "access plus 1 year"

# cache.appcache needs re-requests in FF 3.6 (thanks Remy ~Introducing HTML5)
  ExpiresByType text/cache-manifest       "access plus 0 seconds"

# Your document html
  ExpiresByType text/html                 "access plus 0 seconds"

# Data
  ExpiresByType application/json          "access plus 0 seconds"
  ExpiresByType application/xml           "access plus 0 seconds"
  ExpiresByType text/xml                  "access plus 0 seconds"

# Feed
  ExpiresByType application/atom+xml      "access plus 1 hour"
  ExpiresByType application/rss+xml       "access plus 1 hour"

# Favicon (cannot be renamed)
  ExpiresByType image/x-icon              "access plus 1 week"

# Media: images, video, audio
  ExpiresByType audio/ogg                 "access plus 1 year"
  ExpiresByType image/gif                 "access plus 1 year"
  ExpiresByType image/jpeg                "access plus 1 year"
  ExpiresByType image/webp                "access plus 1 year"
  ExpiresByType image/png                 "access plus 1 year"
  ExpiresByType video/mp4                 "access plus 1 year"
  ExpiresByType video/ogg                 "access plus 1 year"
  ExpiresByType video/webm                "access plus 1 year"


# HTC files  (css3pie)
  ExpiresByType text/x-component          "access plus 1 month"

# Webfonts
  ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
  ExpiresByType application/x-font-ttf    "access plus 1 year"
  ExpiresByType application/x-font-woff   "access plus 1 year"
  ExpiresByType font/opentype             "access plus 1 year"
  ExpiresByType image/svg+xml             "access plus 1 year"

# CSS and JavaScript
  ExpiresByType application/javascript    "access plus 1 year"
  ExpiresByType text/css                  "access plus 1 year"

</IfModule>


# ----------------------------------------------------------------------
# Prevent mobile network providers from modifying your site
# ----------------------------------------------------------------------

# The following header prevents modification of your code over 3G on some
# European providers.
# This is the official 'bypass' suggested by O2 in the UK.

# <IfModule mod_headers.c>
# Header set Cache-Control "no-transform"
# </IfModule>


# ----------------------------------------------------------------------
# ETag removal
# ----------------------------------------------------------------------

# FileETag None is not enough for every server.
<IfModule mod_headers.c>
  Header unset ETag
</IfModule>

# Since we're sending far-future expires, we don't need ETags for
# static content.
#   developer.yahoo.com/performance/rules.html#etags
FileETag None


# ----------------------------------------------------------------------
# Stop screen flicker in IE on CSS rollovers
# ----------------------------------------------------------------------

# The following directives stop screen flicker in IE on CSS rollovers - in
# combination with the "ExpiresByType" rules for images (see above).

# BrowserMatch "MSIE" brokenvary=1
# BrowserMatch "Mozilla/4.[0-9]{2}" brokenvary=1
# BrowserMatch "Opera" !brokenvary
# SetEnvIf brokenvary 1 force-no-vary


# ----------------------------------------------------------------------
# Set Keep-Alive Header
# ----------------------------------------------------------------------

# Keep-Alive allows the server to send multiple requests through one
# TCP-connection. Be aware of possible disadvantages of this setting. Turn on
# if you serve a lot of static content.

# <IfModule mod_headers.c>
#   Header set Connection Keep-Alive
# </IfModule>


# ----------------------------------------------------------------------
# Cookie setting from iframes
# ----------------------------------------------------------------------

# Allow cookies to be set from iframes (for IE only)
# If needed, specify a path or regex in the Location directive.

# <IfModule mod_headers.c>
#   Header set P3P "policyref=\"/w3c/p3p.xml\", CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\""
# </IfModule>


# ----------------------------------------------------------------------
# Start rewrite engine
# ----------------------------------------------------------------------

# Turning on the rewrite engine is necessary for the following rules and
# features. FollowSymLinks must be enabled for this to work.

# Some cloud hosting services require RewriteBase to be set: goo.gl/HOcPN
# If using the h5bp in a subdirectory, use `RewriteBase /foo` instead where
# 'foo' is your directory.

# If your web host doesn't allow the FollowSymlinks option, you may need to
# comment it out and use `Options +SymLinksIfOwnerMatch`, but be aware of the
# performance impact: http://httpd.apache.org/docs/2.2/misc/perf-tuning.html#symlinks

<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>


<IfModule LiteSpeed>
CacheEnable public
RewriteEngine On
RewriteCond %{REQUEST_METHOD} ^GET|HEAD$
RewriteCond %{HTTP_HOST} ^mytestweb.com [NC]
RewriteCond %{REQUEST_URI} !login|admin|register|post|cron    
RewriteCond %{QUERY_STRING} !nocache
RewriteRule .* - [E=Cache-Control:max-age=300]
</IfModule>


# ----------------------------------------------------------------------
# Suppress or force the "www." at the beginning of URLs
# ----------------------------------------------------------------------

# The same content should never be available under two different URLs -
# especially not with and without "www." at the beginning, since this can cause
# SEO problems (duplicate content). That's why you should choose one of the
# alternatives and redirect the other one.

# By default option 1 (no "www.") is activated.
# no-www.org/faq.php?q=class_b

# If you'd prefer to use option 2, just comment out all option 1 lines
# and uncomment option 2.

# IMPORTANT: NEVER USE BOTH RULES AT THE SAME TIME!

# ----------------------------------------------------------------------

# Option 1:
# Rewrite "www.example.com -> example.com".
#aaa
#<IfModule mod_rewrite.c>
#  RewriteCond %{HTTPS} !=on
#  RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
#  RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
#</IfModule>

# ----------------------------------------------------------------------

# Option 2:
# Rewrite "example.com -> www.example.com".
# Be aware that the following rule might not be a good idea if you use "real"
# subdomains for certain parts of your website.

 #<IfModule mod_rewrite.c>
 #  RewriteCond %{HTTPS} !=on
 #  RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
 #  RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
 #</IfModule>


# ----------------------------------------------------------------------
# Built-in filename-based cache busting
# ----------------------------------------------------------------------

# If you're not using the build script to manage your filename version revving,
# you might want to consider enabling this, which will route requests for
# `/css/style.20110203.css` to `/css/style.css`.

# To understand why this is important and a better idea than all.css?v1231,
# please refer to the bundled documentation about `.htaccess`.

# <IfModule mod_rewrite.c>
#   RewriteCond %{REQUEST_FILENAME} !-f
#   RewriteCond %{REQUEST_FILENAME} !-d
#   RewriteRule ^(.+)\.(\d+)\.(js|css|png|jpg|gif)$ $1.$3 [L]
# </IfModule>


# ----------------------------------------------------------------------
# Prevent SSL cert warnings
# ----------------------------------------------------------------------

# Rewrite secure requests properly to prevent SSL cert warnings, e.g. prevent
# https://www.example.com when your cert only allows https://secure.example.com

<IfModule mod_rewrite.c>
  RewriteCond %{SERVER_PORT} !^443   
  RewriteRule ^ https://mytestweb.com%{REQUEST_URI} [R=301,L]
</IfModule>



# ----------------------------------------------------------------------
# Prevent 404 errors for non-existing redirected folders
# ----------------------------------------------------------------------

# without -MultiViews, Apache will give a 404 for a rewrite if a folder of the
# same name does not exist.
# webmasterworld.com/apache/3808792.htm

Options -MultiViews


# ----------------------------------------------------------------------
# Custom 404 page
# ----------------------------------------------------------------------

# You can add custom pages to handle 500 or 403 pretty easily, if you like.
# If you are hosting your site in subdirectory, adjust this accordingly
#    e.g. ErrorDocument 404 /subdir/404.html
ErrorDocument 404 /404.html


# ----------------------------------------------------------------------
# UTF-8 encoding
# ----------------------------------------------------------------------

# Use UTF-8 encoding for anything served text/plain or text/html
AddDefaultCharset utf-8

# Force UTF-8 for a number of file formats
AddCharset utf-8 .atom .css .js .json .rss .vtt .xml


# ----------------------------------------------------------------------
# A little more security
# ----------------------------------------------------------------------

# To avoid displaying the exact version number of Apache being used, add the
# following to httpd.conf (it will not work in .htaccess):
# ServerTokens Prod

# "-Indexes" will have Apache block users from browsing folders without a
# default document Usually you should leave this activated, because you
# shouldn't allow everybody to surf through every folder on your server (which
# includes rather private places like CMS system folders).
<IfModule mod_autoindex.c>
  Options -Indexes
</IfModule>

# Block access to "hidden" directories or files whose names begin with a
# period. This includes directories used by version control systems such as
# Subversion or Git.
<IfModule mod_rewrite.c>
  RewriteCond %{SCRIPT_FILENAME} -d [OR]
  RewriteCond %{SCRIPT_FILENAME} -f
  RewriteRule "(^|/)\." - [F]
</IfModule>

# Block access to backup and source files. These files may be left by some
# text/html editors and pose a great security danger, when anyone can access
# them.
<FilesMatch "(\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$">
  Order allow,deny
  Deny from all
  Satisfy All
</FilesMatch>

# If your server is not already configured as such, the following directive
# should be uncommented in order to set PHP's register_globals option to OFF.
# This closes a major security hole that is abused by most XSS (cross-site
# scripting) attacks. For more information: http://php.net/register_globals
#
# IF REGISTER_GLOBALS DIRECTIVE CAUSES 500 INTERNAL SERVER ERRORS:
#
# Your server does not allow PHP directives to be set via .htaccess. In that
# case you must make this change in your php.ini file instead. If you are
# using a commercial web host, contact the administrators for assistance in
# doing this. Not all servers allow local php.ini files, and they should
# include all PHP configurations (not just this one), or you will effectively
# reset everything to PHP defaults. Consult www.php.net for more detailed
# information about setting PHP directives.

# php_flag register_globals Off

# Rename session cookie to something else, than PHPSESSID
# php_value session.name sid

# Disable magic quotes (This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.)
# php_flag magic_quotes_gpc Off

# Do not show you are using PHP
# Note: Move this line to php.ini since it won't work in .htaccess
# php_flag expose_php Off

# Level of log detail - log all errors
# php_value error_reporting -1

# Write errors to log file
# php_flag log_errors On

# Do not display errors in browser (production - Off, development - On)
# php_flag display_errors Off

# Do not display startup errors (production - Off, development - On)
# php_flag display_startup_errors Off

# Format errors in plain text
# Note: Leave this setting 'On' for xdebug's var_dump() output
# php_flag html_errors Off

# Show multiple occurrence of error
# php_flag ignore_repeated_errors Off

# Show same errors from different sources
# php_flag ignore_repeated_source Off

# Size limit for error messages
# php_value log_errors_max_len 1024

# Don't precede error with string (doesn't accept empty string, use whitespace if you need)
# php_value error_prepend_string " "

# Don't prepend to error (doesn't accept empty string, use whitespace if you need)
# php_value error_append_string " "

# Increase cookie security
<IfModule mod_php5.c>
  php_value session.cookie_httponly true
</IfModule>


via Chebli Mohamed

How to direct random routing to one view page in laravel?

i want to direct random link to only one view except that i've define

e.g : localhost:8000/abxcdss

and it will go to a view or home page.



via Chebli Mohamed

Formatting number in Eloquent query or Yarja Datatables

I am writing a searchable table which includes the area and population. Here is the basic query:

public function getCountryData()
  {
    $co = DB::table('countries')->leftJoin('country_detail','country_detail.country_id','=','countries.id')->addSelect(['countries.id','countries.name','country_detail.capital','country_detail.area','country_detail.iso3','country_detail.population','country_detail.currencyName','country_detail.phone','country_detail.continent'])->get();
    return Datatables::of($co)
    ->addColumn('action', function($co){
                            $btn = '<div style="float:right">
                            <a href="'. route('country.edit',$co->id) .'  " class="btn btn-outline-secondary btn-xs" title="edit" style="margin-right:.5em">'.getEditIcon().'</a><a href="'. route('country.show', $co->id) .'" class="btn btn-outline-secondary btn-xs" title="images" style="margin-right:.5em">'.getBinoculars().'</a>';

                             return $btn;
                     }) ->rawColumns(['action'])
                 ->make(true);

  }

All this works fine in my view except that the population field, for example, returns something like 29121286 and of course I want to format it so it is 29,121,286.

Can this be done in the query or something in Datatables itself?



via Chebli Mohamed

how do i integrate functionality in my laravel website if a user post an advert from my website it will also post on facebook

As i ask a question to you all how can i achieve this functionality in laravel website if a user come my site and post an advert of cars then how this currently added advert will post to facebook any idea please share only logic and ideas and if laravel packages for this kind of works please share.



via Chebli Mohamed

Creating a subquery using laravel eloquent

My raw query working fine. but after converting laravel eloquent it's not working

SELECT
    key_vals.`key`,
    key_vals.`value`
FROM
    key_vals
WHERE TIMESTAMPDIFF(MINUTE,
        key_vals.`last_store_time`,
        now()) < (SELECT ttl from ttls) 


via Chebli Mohamed

Setting selected option in laravel from database

I have a problem here, I want to make an edit form, I want the province that appears in the edit form to be the province selected from the database, here my code

  <select name="provinsi" id="provinsi" class="form-control">
                <option value="">Pilih Provinsi</option>
                @foreach ($province as $prov)
                <option value=""></option>
                @endforeach
            </select>

here my controller code

public function ShowSantri(Request $request,$id)
    {

        $province = DB::table('provinces')->get();
        $profiles = Profile::find($request->id);

        return view('admin/modal/edit_santri',compact('profiles','province'));


via Chebli Mohamed

Laravel - How to send forgot password email on different email providers?

How I can send email on different email providers like (gmail, abv.bg, mail.bg, yahoo.com and etc...) in Laravel. Is it hard to implement mechanism which determines email provider and send email without configuration. I will be very thankful if u help me!



via Chebli Mohamed

Convert data in Laravel 5.8 dive wrong result

I am beginner in Laravel. I use in my project Laravel 5.8. I have this code:

$dataTimeFromDb = '2019-12-28T23:54:04.000000Z';
$userLastActivity = Carbon::parse($dataTimeFromDb)->format('Y-m-d H:m');

In result I have: 2019-12-29 00:12.

I need value from DB in format: Y-m-d H:m. My timezone is Warsaw/Berlin and I save in this format in DB.

How can I repeir it?



via Chebli Mohamed

samedi 28 décembre 2019

How can last row if last row is 003

how do I add +1 data if the last data type varchar data is in format 001, 002, 003 , i try that but results is 1

 $nis = Profile::all()->last();
        $nisnow = $nis->nis += 1;
        dd($nisnow);

Edited : my expect results if last data 003 + 1=004



via Chebli Mohamed

How to move from npm to yarn in my laravel, vue/cli apps?

I want to move from npm to yarn in my laravel, vue/cli apps and viewing / reading some tutorials I see yarn.lock file mentioned ion the root of the app. But running command for new laravel app creation: laravel new ya_prj I do not any yarn.lock or yarn.* files in newly created project I have yarn installed :

$ yarn --version                  
0.32

Did I miss some options?

Also how can I to replace npw with yarn for my laravel 5.7-6, vue/cli 4 apps locally and on live server?

Thanks!



via Chebli Mohamed

Laravel 5.8 Class 'Form' not found

Using laravel 5.8 and im trying to use Form and when i load the page it outputs the error class 'Form' not found. Is there a way to fix this in version 5.8 i've searched for solutions and all I can find is a fix for other versions.

Thanks



via Chebli Mohamed

Use of Laravel query builder methods

I am using laravel6. My question, can we use laravel updateOrInsert query builder method with eloquent ORM. If yes, How please a sample.



via Chebli Mohamed

Laravel lost locale after login

I am very beginner in Laravel. I use Laravel 5.8 in my project. I have middleware in my project with code:

class Localization
{
    public function handle($request, Closure $next)
    {
        if (session()->has('locale')) {
            App::setLocale(session()->get('locale'));
        }
        return $next($request);
    }
}

I have translation file in:

  • resources/lang/de/messages.php

  • resources/lang/en/messages.php

  • resources/lang/pl/messages.php

When I login in my website I lost translation. I have the default language (Polish). How can you fix this?



via Chebli Mohamed

export bulk data - PHP laravel

I m working on a platform and i’m stuck with few issues, please help me out.

I have built a Laravel application(Kind of ecommerce), where users will log in to our store and selects the products they want to sell in their platform(Shopify, Magento, Zencart etc.) add them to their catalog/cart. the users can add up to 15-20K products at a time to sell in their platform.

In their catalog, they have an option o export these product's details in a csv file, but it's taking to much load and end with crashing the browser. is there any way to tackle this issue? instead of loading the data over browser, can we anyhow create the CSV file in the backend of the servers and once its ready we can link it up?

Thank you all!



via Chebli Mohamed

Laravel not sending emails on GoDaddy shared hosting

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=babuliprasadsinghxxx@gmail.com
MAIL_PASSWORD=xxxx
MAIL_ENCRYPTION=tls

This settings working good on localhost but after uploading on godaddy hosting server email is not sending please help me



via Chebli Mohamed

How to validate 2 Laravel fields in a NAND way

I'm looking for a solution to the following case: my controller action receives 2 variables, however they must exclude eachother. So you can pass either 1 of them or none.

The following truth table arises (NAND):

| A | B | Result |
|---|---|--------|
| 0 | 0 |   1    |
| 0 | 1 |   1    |
| 1 | 0 |   1    |
| 1 | 1 |   0    |

(say A equals points and B equals coupon).

// MyController.php
$this->validate($request, [
    'points' => '',
    'coupon' => ''
]);

I've tried some solutions like nullable|required_without:field_name but those seem to result in an XOR, which means you must pass at least 1 of them.



via Chebli Mohamed

How can i write query in laravel with where clause?

Store below json record in database table field 'contact_info'

{
  "invoice":{
    "number":"gthy",
    "invoiceDate":"2019-12-25 17:20:08",
    "invoiceDueDate":"2020-01-01 17:20:08",
    "paymentTerms":"7"
  },
  "company":{
    "name":"Test ",
    "address":"Test",
    "city":"Test",
    "state":"Test",
    "country":"Test",
    "pincode":"Test",
    "email":"Test@gmail.com",
    "currency_code":"USD"
  },
  "sender":{
    "name":"Test",
    "address":"Test",
    "city":"Test",
    "state":"Test",
    "country":"Test",
    "pincode":"Test",
    "email":"Test"
  }
}

I need to applied where condition with 'invoiceDueDate' this field in Laravel. So how can i write query for this? Please suggest me.



via Chebli Mohamed

Update image in vue and laravel works with some errors

I have a form to store and update data including an image, however when I try to Store Or update Image with another Image that breaks my validation rule the validation works fine but if I try to re-update any record without including image I get the same validation message like if I'm updating with invalid image it doesn't work fine back till I store or update including upload a valid Image then every thing works fine in store or update even if updating without image. Note:The store and update work fine if all data are valid in the first time.

This is my form

<template>
<form class="border border-info rounded" style="padding: 0px 15px 15px 15px;">
    <button @click="resetForm" type="button" data-toggle="tooltip" title="Reset Form" class="close" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
    <div style="width: 100%;">
        <div style="float:left; width: 40%">
            <div class="form-group" style="padding-top: 25px; margin-top: 20px; width: 343px;">
                <input v-model="channel.name"
                       name="name"
                       type="text"
                       maxlength="100"
                       class="form-control"
                       placeholder="Channel title"
                       required="required" />
            </div>
            <div class="form-group">
                <div class="row" style="margin: 40px 0 35px 0">
                    <label style="padding-top: 5px">Base color</label>
                    <input v-model="channel.baseColor"
                           name="base_color"
                           type="color"
                           class="form-control color-picker"
                           style="margin-left: 229px;"
                           data-toggle="tooltip" title="Pick Color"/>
                </div>
            </div>
            <div class="form-group">
                <div class="row" style="margin: 40px 0 35px 0">
                    <label style="padding-top: 5px">Complementary color</label>
                    <input v-model="channel.complementaryColor"
                           name="complementary_color"
                           type="color"
                           class="form-control color-picker"
                           style="margin-left: 150px;"
                           data-toggle="tooltip" title="Pick Color"/>
                </div>
            </div>
        </div>
        <div class="form-group" style="float:right; width: 40%">
            <image-upload :avatar="channel.avatarUrl"></image-upload>
        </div>
    </div>

    <button
        @click.prevent="editing ? updateChannel() : addChannel()"
        type="submit" class="btn btn-outline-primary btn-block"
        v-text="editing ? 'Update Channel' : 'Add Channel'">
    </button>
</form>
</template>

<script>
import ImageUpload from '../../ImageUpload';

class Channel {
    constructor(channel){
        this.name = channel.name || "";
        this.avatarUrl = channel.avatar_path || "";
        this.baseColor = channel.bg_base_color || "";
        this.complementaryColor  = channel.bg_complementary_color || "";
    };
}

const data = new FormData();

export default {
    name: "AddEditChannel",
    components: {ImageUpload},
    data() {
        return {
            channel: new Channel({}),
            editing: false,
            channelId:'',
            file: null
        }
    },
    created() {
        this.$parent.$on('edit_channel', ({channel}) => {
            this.resetForm();
            this.editing = true;
            this.channelId = channel.id;
            this.channel = new Channel(channel);
        });
        //
        this.$on('avatar_loaded', (avatar) => {
            this.channel.avatarUrl = avatar.src;
            this.file = avatar.file;
        });
    },
    methods: {
        resetForm() {
            this.channel = new Channel({});
            this.channelId = '';
            this.file = null;
            this.editing = false;
        },
        addChannel() {
                data.append('name', this.channel.name);
                data.append('base_color', this.channel.baseColor);
                data.append('complementary_color', this.channel.complementaryColor);
                data.append('avatar', this.file);

                data.append('_method', 'POST');

                axios.post('/dashboard/channels', data).then(resp => {
                    this.$parent.$emit('channel_created', resp.data)
                }).catch(error => {
                    flash(error.response.data, 'danger', 'backEndStyle');
                });

                this.resetForm();

        },
        updateChannel() {
                data.append('id', this.channelId);
                data.append('name', this.channel.name);
                data.append('base_color', this.channel.baseColor);
                data.append('complementary_color', this.channel.complementaryColor);
                if (this.file){
                    data.append('avatar', this.file);
                }

                data.append('_method', 'PUT');

                axios.post(`/dashboard/channels/${this.channelId}`, data).then(resp => {
                    this.$parent.$emit('channel_updated', resp.data);
                }).catch(error => {
                    flash(error.response.data, 'danger', 'backEndStyle');
                });

                this.resetForm();
        }
    }
}
</script>

this is validation request for my image

public function rules()
{
    $avatrAttr = 'required|image|mimes:jpg,jpeg,png|max:50|dimensions:max_width=600,max_height=600';

    if($this->isMethod('POST')) {
        return [
            'avatar' => $avatrAttr,
        ];
    }  else {
        if ($this->has('avatar') && $this->hasFile('avatar')){
            return [
                'avatar' => $avatrAttr,
            ];
        }
    }
}

this is a Trait to handle image upload

public function verifyAndStoreImage($request, $oldImg = null, $fieldname = 'avatar', $directory) {

    if ($request->file($fieldname)->isValid()) {

        if ($oldImg != null) {
            $this->RemoveOldImg($oldImg);
        }

        return $request->file($fieldname)->store($directory, 'public');

    }

    return $oldImg;

}

the Controller for store and update

public function store(ChannelRequest $channelRequest, AvatarRequest $avatarRequest)
{
    $channel = Channel::create([
        'name' => $channelRequest->name,
        'bg_base_color' => $channelRequest->base_color,
        'bg_complementary_color' => $channelRequest->complementary_color,
        'avatar_path' => $this->verifyAndStoreImage($avatarRequest, null, 'avatar', 'avatars/channels')
    ]);

    return response($channel, 200);
}

/**
 * Update the specified resource in storage.
 *
 * @param ChannelRequest $channelRequest
 * @param Channel $channel
 * @return \Illuminate\Http\Response
 */
public function update(ChannelRequest $channelRequest, Channel $channel, AvatarRequest $avatarRequest)
{
    $channel->update([
        'name' => $channelRequest->name,
        'bg_base_color' => $channelRequest->base_color,
        'bg_complementary_color' => $channelRequest->complementary_color,
        'avatar_path' => $this->verifyAndStoreImage($avatarRequest, $channel->avatar_path, 'avatar', 'avatars/channels')
    ]);

    return response($channel->fresh(), 200);
}


via Chebli Mohamed

vendredi 27 décembre 2019

laravel:database employee list using to generate bulk qrcode generator

laravel generate qrcode using employee list using their id and show on particular page and extra select unselect id to custom generator from front-end.and print selected id's qrcode

here my view :

<?php echo QrCode::size(265)->generate($row->id) ?>


via Chebli Mohamed

How to save a images in public_html instead of the default storage in laravel?

**************************skip this**************************************************

I can't create symlink() some "symlink() has been disabled for security reasons" BS!!

I already bought the hosting service for a full year, fee non refundable, no ssh support, i had casually figured "it just needs cpanel and i'll upload my laravel project" yet rn i cant get it to load a single image. ****************************************************************************************

How to save images to public_html lets say to a file storage/cover_image

if($request->hasFile('cover_image')){
            // Get filename with the extension
            $filenameWithExt = $request->file('cover_image')->getClientOriginalName();
            // Get just filename
            $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
            // Get just ext
            $extension = $request->file('cover_image')->getClientOriginalExtension();
            // Filename to store
            $fileNameToStore= $filename.'_'.time().'.'.$extension;
            // Upload Image
       Storage::disk('my_upload')->put($fileNameToStore, $request->file('cover_image'));
            //$path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
        } else {
            $fileNameToStore = 'noimage.jpg';
        }

I made a custom disk in called my_upload i cant figure out where it saves the file but it doesn't save in public_html/storage/cover_images

//custom my_disk code
'my_upload' => [
        'driver' => 'local',
        'root' => public_path().'/storage/cover_images',
        'visibility' => 'public',
    ],

if i use storeAs it always stores storage that is not in public_html its also not an issue with permissions since am still testing i have set the permissions to 777



via Chebli Mohamed

How remove duplicates from Laravel equivalent result

I beginner in Laravel. I use in my project Laravel 5.8. I have this code:

Schema::create('db_id', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id1')->nullable();
            $table->foreign('user_id1')->references('id')->on('users')->onDelete('cascade');
            $table->unsignedBigInteger('user_id2')->nullable();
            $table->foreign('user_id2')->references('id')->on('users')->onDelete('cascade');
            $table->string('token', 240);
            $table->char('status', 1)->default(0);
            $table->dateTime('last_message')->nullable();
            $table->dateTime('read_at')->nullable();
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';
        });

When I run this code:

DbID::where('user_id2', '=', Auth::user()->id)->orWhere('user_id1',  Auth::user()->id)->orderBy('last_message', 'DESC')->get();

Sometimes I have duplications.

In my db I have record with user_id2 and user_id1 - Auth::user()->id.

I need show this record only one.

How can I fix it?



via Chebli Mohamed

uploading multple image in laravel and vue this code not work perfectly

  1. I tried so many time but it's not working correctly. when I upload 3 images but its only upload 2 images but when I upload 4 Image its only upload 2 images. How many images above 1 I upload it's only work for two images

    Laravel Code

    [I think laravel code does not work][1] $multipleImages=$request['sub_image']; for($i=1; $iresize(200,200); $public_path=public_path()."/sub-Image/"; $image->save($public_path.$name); }

    Vue JS Code :[its working correctly][2]  SubimageUpload(e) {
      for (let i= e.target.files.length-1; i>=0; i--) {
      var fileReader = new FileReader();
       fileReader.readAsDataURL(e.target.files[i]);
        fileReader.onload = e => {
        this.form.sub_image[i] = e.target.result;
      };
    
      }
      console.log(this.form);
      },
    

    [1]: https://i.stack.imgur.com/i8wGW.png [2]: https://i.stack.imgur.com/QCHHj.png



via Chebli Mohamed

Access variable across methods Laravel PHP

Hey all actually I too facing the problem but I couldn't understand any of the above methods. Please help me to understand those stuffs and help t fix my problem.

I have two methods method1 and method2, where I receive some value in method 1 which needs to used in method 2. I created a variable on class level but I couldn't access the variable below is the code snippet.

class testController extends controller { 
        public $isChecked = false;
        public $isSelectedValue = 0;
public function ValidateValue(Request $req) {
        $isChecked = $req->checked;
        $isSelectedValue = $req->value;
     }
public function UsethoseValues() {
        if($isChecked) { // I can't use the variable here it throws run time error. I need help on this please help.
           }
     }
}


via Chebli Mohamed

how to get laravel response the same page after login with ajax?

i have a login form to login a user i want to know about how to get laravel response in ajax success function. if submit the form i was got a object('status':'msg') in http://127.0.0.1:8000/login page. but i want to just redirect user correct page after login with macing alert. please help me to learn laravel with ajax function.

form

<form id="loginForm" method="POST" action="">
       @csrf
 <input id="email" type="email" class="form-control  name="email" value="" 
   required autocomplete="email" autofocus>

 <input id="password" type="password" class="form-control name="password" required 
    autocomplete="current-password">

 <button type="submit" class="btn btn-primary">LOGIN</button>
</form>

ajax: after document ready

$('#loginForm').submit(function(e){
    e.preventDefault();
    var formInput = $(this);
        $.ajax({
                type:'POST',
                url: 'login',
                data: formInput.serialize(),
                dataType: 'json',
                cache: false,
                success:function(status){
                    if(status== "success"){ 
                          alert("your in");
                       }
                        },
                        error:function(status){
                        if(status== "error"){ 
                          alert("no data found");
                       }
                        }
                    })
                });     

Route:

Route::post('login','loginController@login')->name('loginData'); 

Controller:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use Session;
class loginController extends Controller
{
    public function login(Request $request){
        $credentials = $request->only('email', 'password');
        if (Auth::attempt($credentials)) {
          //  print_r($request->all());

            session()->put('role', Auth::user()->Role);

            $request->session()->flash('message', 'New customer added successfully.');
            $request->session()->flash('message-type', 'success');
           return response()->json(['status'=>'success']);
           return back();

        }else{
            $request->session()->flash('message', 'you have entered an invalid email address or password. please try again');
            $request->session()->flash('message-type', 'danger');
            return response()->json(['status'=>'error']);
            return back();
        }

    }
}


via Chebli Mohamed

How to show on heatmap(lat and long) above one lakh in vue js? Heatmap not showing all record. below my code

please see screen. lat-long not showing above one lac record on heatmap. https://i.stack.imgur.com/DvMS7.png



via Chebli Mohamed

Trait method hasTooManyLoginAttempts has not been applied

I have upgraded my project from 5.2 to 5.3 in laravel. after that, I have the following error:-

Trait method hasTooManyLoginAttempts has not been applied, because there are collisions with other trait methods on App\Http\Controllers\Auth\AuthController in D:\xampp1\htdocs\clubmart_frontend\ app\Http\Controllers\Auth\AuthController.php on line 19

Following is the code of my AuthController:-

<?php

namespace App\Http\Controllers\Auth;

use App\Contracts\Repositories\UserRepositoryInterface;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Voucher;
use App\Services\CartManager;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Validator;
use Illuminate\Http\Request;
use App\Events\UserWasRegistered;
use Event;
use Auth;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesUsers, RegistersUsers {
        AuthenticatesUsers::redirectPath insteadof RegistersUsers;
        AuthenticatesUsers::guard insteadof RegistersUsers;
    }

    use ThrottlesLogins;

    public $guard = 'web';

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /** @var UserRepositoryInterface */
    protected $userRepository;

    /**
     * Create a new authentication controller instance.
     *
     * @param UserRepositoryInterface $userRepository
     */
    public function __construct(UserRepositoryInterface $userRepository)
    {
        $this->userRepository = $userRepository;
        $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array $data
     *
     * @return Validator
     */
    protected function validator(array $data)
    {
        return Validator::make(
            $data,
            [
                'first_name' => 'required|max:255',
                'last_name'  => 'required|max:255',
                'email'      => 'required|email|max:255|unique:users',
                'password'   => 'required|min:6|confirmed',
            ]
        );
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array $data
     *
     * @return User
     */
    protected function create(array $data)
    {
        return $this->userRepository->create(
            [
                'name'       => $data['email'],
                'first_name' => $data['first_name'],
                'last_name'  => $data['last_name'],
                'email'      => $data['email'],
                'password'   => $data['password'],
            ]
        );
    }
    protected function authenticated(Request $request, User $user)
    {
        if($user = Auth::user()) {
            if(!empty(app(CartManager::class)->getItems())) {
                return redirect()->intended('/cart');
            }
            else {
                return redirect()->intended('/');
            }
        }
        else {
            return redirect()->intended('/');
        }
    }
    //overwrite for add flash message to session
    public function postRegister(Request $request, User $user)
    {

        $validator = $this->validator($request->all());
        if ($validator->fails()) {
            $this->throwValidationException(
                $request, $validator
            );
        }

        //login the newly created user
        \Auth::login($this->create($request->all()));

        //fire up the send user email event
        $user_id =  $user->find(\Auth::user()->id);
        Event::fire(new UserWasRegistered($user_id));

        $request->session()->flash('alert-success', 'Registration successful!');
        if(!empty(app(CartManager::class)->getItems())) {
            return redirect()->intended('/cart');
        }
        else {
            return redirect($this->redirectPath());
        }
    }

    /**
     * Log the user out of the application.
     * overwrite for clear user from session
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    {
        if($request->session()->has('user_id'))
            $request->session()->forget('user_id');

        \Auth::guard($this->getGuard())->logout();

        return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
    }


}

This is the code of Controller.php:-

<?php

namespace App\Http\Controllers;

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

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

Any help will be appreciated. thanks in advance.



via Chebli Mohamed