jeudi 30 septembre 2021

Laravel FakeID problem Missing required parameter for Route

i trying to use this package to hide the id of my users, tthe problem is that can't get it to work

https://github.com/Propaganistas/Laravel-FakeId

Error:

Missing required parameter for [Route: perfil] [URI: perfil/{id}] [Missing parameter: id]. 

Route:

Route::get('/perfil/{id}', 'PerfilesController@index')->name('perfil');

Blade:

 <a href="">     <p class="">Jimmy Turner</p> </a>

Controller:

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


  $usuario =  User::where('id', $id)->first();


    $data = [
        'category_name' => 'users',
        'page_name' => 'profile',
        'has_scrollspy' => 0,
        'scrollspy_offset' => '',

    ];
    return view('perfil',compact('usuario'))->with($data);

}

In the User model it is configured with:

use Propaganistas\LaravelFakeId\RoutesWithFakeIds;

 class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, RoutesWithFakeIds;

Why can't you find the fake ID?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/39TRsVP
via IFTTT

How to alias in Laravel Eager Loading Array without changing method name

I need to alias when I do a Laravel eager loading:

$employee = Employee::with(['profilepic', 'emp_company'])->find($user->employee_id);

In my model I have profilepic function and emp_company function. I need to pass a company object without renaming the emp_company funtion to company.

I need to to this because I want the JSON response as profilepic and company. for the frontend I need emp_company object as company. It is possible to alias.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3kVHYjm
via IFTTT

mercredi 29 septembre 2021

Expected response code 250 but got code "530", with message "530-5.7.0 Authentication Required

I've deployed my web app on Heroku but there are some things which are giving me an error when I'm trying to register a new user in the web app. The registration works fine on my localhost and it even sends the new users an email whenever they register an account. But on heroku, it displays the following error whenever I try to register an new user. 'Expected response code 250 but got code "530", with message "530-5.7.0 Authentication Required'.

I've also noted that the .env file doesn't show on my github whenever I push so I had to put the env file on heroku config settings.

Here's my code on my .env file and mail.php.

MAIL_MAILER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
MAIL_USERNAME=ben@gmail.com
MAIL_PASSWORD=****************
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=ben@gmail.

'default' => env('MAIL_MAILER', 'smtp'),
'from' => [
    'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
    'name' => env('MAIL_FROM_NAME', 'Example'),
],

And here are my setting on heroku displayed on this image..

If you can, please show me a way of how to get around this error.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3ijRStb
via IFTTT

Dynamic row value insertion to the database [duplicate]

i have a recipe form of which ingredient, unit and quantity fields row can be added dynamically, I wanted to add these field into a single column named ingredient in database.

for now, the first row values is inserted in db as {"ingredients":["flour"],"quantity":["2"],"unit":["cup"]}

How can i insert the added row data too in this column? ingredient is the column where i want to insert these datas. Can you explain it with an example?

I know its the basic thing for you, but as a beginner its bit difficult for me to understand. Please help me out. Thank you!



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3kPZ2qR
via IFTTT

mardi 28 septembre 2021

enciphered URLs laravel

how to make the encryption shorter in characters?

\Crypt::encrypt($event->id))

Result:

http://myurl/id/eyJpdiI6Im5ub0hyaWJwVE1iendYbHNaSzJsSXc9PSIsInZhbHVlIjoiVHhpNmF4b3NlQjk2NFluRXhCOFZuQT09IiwibWFjIjoiZDkxNzk2OTlmZGRmZWJjYjFlNjExYjcyNWU4Y2Y4NWYwMjYxMTkxN2ZmNzU3NGM4Nzg0OWJkNjk1NmExNjVkZiIsInRhZyI6IiJ9

generates a very large link, I need to shorten it, is it possible?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3EXmdrb
via IFTTT

Heroku app won't redirect unlike when it's running on localhost

I've been building and running a web app on my localhost. Everything was working fine after I carried out all the test to make sure everything was working fine. I finally decided to deploy the web app on heroku, where I wanted to add extra content on the landing page through by using the admin section.

Now, I face the problem when I try to register a new user. After I've clicked the register link and fill out all the fields. The site redirects me to a blank page displaying '500 | Server Error.' instead of redirecting me to the login page where I can access the website and add content. This is an image of the page which it redirects me to. Image instead of redirecting me to a page like this. Can some please guide me on a way of how to solve this problem? If you want to try out the site, here's the link. http://lifeisspiritual.herokuapp.com/register



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3zI4WhS
via IFTTT

Trying to get property 'domain' of non-object Laravel

// Get the link details $link = Link::active()->where('slug', $slug)->with(['user', 'pixels', 'scripts', 'cta', 'domain'])->first();

    // If the domain does not belong to the system
    if ($domain != config('settings.link_shorten_domain') ) {

       
        // Make sure the link domain match what is in the db
        if (  $link->domain['name'] != $domain )
            return redirect()->away( config('app.url') ); 

    }


     // Redirect to homepage if the link doesn't exist
    if ( ! $link )
        return redirect()->away( config('app.url') );


    // Check the feature usage ability
    // Only check for non admin users


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ZtIaxI
via IFTTT

lundi 27 septembre 2021

Illuminate\Database\QueryException : could not find driver - Laravel 5.8

I have a Laravel 5.8, running locally on my macOS Big Sur 11.4

"laravel/framework": "5.8.*",


Terminal

php --version

WARNING: PHP is not recommended                                                                                        
PHP is included in macOS for compatibility with legacy software.                                                       
Future versions of macOS will not include PHP.                                                                         
PHP 7.3.24-(to be removed in future macOS) (cli) (built: May  8 2021 09:40:37) ( NTS )                                 
Copyright (c) 1997-2018 The PHP Group                                                                                  
Zend Engine v3.3.24, Copyright (c) 1998-2018 Zend Technologies

Web Server

I checked phpinfo();, enter image description hereI see

Loaded Configuration File

/Applications/MAMP/bin/php/php7.4.12/conf/php.ini.


....

[PostgreSQL]
; Allow or prevent persistent links.
; http://php.net/pgsql.allow-persistent
pgsql.allow_persistent = On

; Detect broken persistent links always with pg_pconnect().
; Auto reset feature requires a little overheads.
; http://php.net/pgsql.auto-reset-persistent
pgsql.auto_reset_persistent = Off

; Maximum number of persistent links.  -1 means no limit.
; http://php.net/pgsql.max-persistent
pgsql.max_persistent = -1

; Maximum number of links (persistent+non persistent).  -1 means no limit.
; http://php.net/pgsql.max-links
pgsql.max_links = -1

; Ignore PostgreSQL backends Notice message or not.
; Notice message logging require a little overheads.
; http://php.net/pgsql.ignore-notice
pgsql.ignore_notice = 0

; Log PostgreSQL backends Notice message or not.
; Unless pgsql.ignore_notice=0, module cannot log notice message.
; http://php.net/pgsql.log-notice
pgsql.log_notice = 0

Lately, I can not run php artisan migrate successfully, I kept getting :

Illuminate\Database\QueryException : could not find driver (SQL: select * from information_schema.tables where table_schema = public and table_name = migrations and table_type = 'BASE TABLE')

I'm using psql not MySQL.

DB_LOCAL_CONNECTION=pgsql
DB_LOCAL_HOST=localhost
DB_LOCAL_PORT=5432
DB_LOCAL_DATABASE=dbName
DB_LOCAL_USERNAME=postgres
DB_LOCAL_PASSWORD=

How can I get it to work again ?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3oidmut
via IFTTT

samedi 25 septembre 2021

show timeout when try to export large data in excel using laravel

I am trying to export more than 10k data in my excel but it show time out or sometime show not reached. What is the best process to export large amount of data in excel. In the i gave mtycontroller and export code.

controller:

function excel(){
        return (new UsersExport())->download('invoices.xlsx');
    }

in the Export folder UsersExport.php file

<?php

namespace App\Exports;

use App\Models\TEST;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\FromArray;
use Illuminate\Contracts\Queue\ShouldQueue;

class UsersExport implements  FromQuery, WithMapping, WithHeadings,ShouldQueue
{
    /**
    * @return \Illuminate\Support\Collection
    */   
    use Exportable;

    public function query()
    {
        return TEST::query()->where('status_id','!=','12');
    }
    
    public function headings(): array
    {
        return [
           'test Id', 'test Tracking Id','test Type','customer name', 'Receiver Info','Pickup','Delivery','cash','Charge','Status','cash Payment','Paid By','Request Time','Pickup Time','Delivery Time','Time Duration'
        ];
    }
    
    public function map($row): array
    {
      if($row->delivery == '0' || empty($row->delivery)){
          $delivery = (!empty($row->branch->name)?$row->branch->name:'Not Available');
      }else{
          $delivery=(!empty(\App\Models\Branch::find($row->delivery)->name)?\App\Models\Branch::find($row->delivery)->name:'Not Available');
      }  

      $picks =\App\Models\TestLog::where('courier_id',$row->id)->where('status_id','13')->first();
        return [
             $row->id,
              $row->tracking_id,
              $row->test_type->title,
              !empty($row->customer->name)?$row->customer->name:"Not Available",
              $row->receiver_name.'-- '. $row->receiver_address .'-- '.$row->receiver_phone,
              !empty($row->pickup->name)?$row->pickup->name:"Not Available",
              !empty($delivery)?$delivery:"Not Available",
             $row->cash,
             $row->pricing->price,
             $row->status->name,
             $row->cash_status,
             $row->paid_by,
            date('d-m-Y h:i A',strtotime($row->created_at)),
             !empty($picks->created_at)?date('d-m-Y h:i A',strtotime($picks->created_at)):"Not Available",
            !empty($row->delivery_date)?date('d-m-Y h:i A',strtotime($row->delivery_date)):"Not Available",
             $row->created_at->diffForHumans()
        ];
    }  
}

Code is ok. it exports data when it has less amount of data but its occur problem when it's time to export large amount of data. Please if anyone can suggest how can i solved this when it's time to export large data



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3CK6hXq
via IFTTT

how can i access sessions on laravel?

i can access the Session::get('LoggedUser') on the index function with no problem.

enter image description here

but i can't access the session when i send an axios post request to the getProjects() function.

enter image description here

Controller code:

class ProjectController extends Controller
{
    public function index(){
        //dd(Session::get('LoggedUser'));
        return view('user.project.dashboard');
    }

    public function getProjects(){
        dd(Session::get('LoggedUser'));
    }
}

compnent code:

mounted(){
            axios.post('/api/user/projects')
                .then(response=>{
                    console.log(response.data.data)
                })
        }

api.php:

Route::prefix('user')->group(function(){
    Route::post('projects',[UserProjectController::class, 'getProjects']);
});


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/39DISuk
via IFTTT

vendredi 24 septembre 2021

No input file specified. CPANEL/PHP

My Laravel application has been on my Cpanel for over 3years. Today it started throwing Error No input file specified. when you visit my website.

I move the same code to a subdomain text.lamxxx.com and it work FINE. But on my main domain is still throwing No input file specified. I have been troubleshooting for over 24hrs.I checked the Server Log, check laravel log etc. But The website is still down.

BELOW IS MY .htacces

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

# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php73” package as the default “PHP” programming language.
<IfModule mime_module>
  AddHandler application/x-httpd-ea-php73 .php .php7 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit``` 


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3i4OJgT
via IFTTT

how can i load fast start page with ajax or post using route

I've tried using post and @include

the code i use

route

Route::post('/home/section/home_categories','HomeController@load_home_categories_section')->name('home.section.home_categories');

view blade

<div id="section_home_categories">
    
</div>

Script

   $(document).ready(function(){
         $.post('', {_token:''}, function(data){
             $('#section_home_categories').html(data);
             AIZ.plugins.slickCarousel();
         });
    });

when I use POST and click on items in categories then click back the page position is in the footer, therefore I use @include('frontend.partials.home_categories_section') the impact when loading the initial page becomes long



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2XGUqtW
via IFTTT

jeudi 23 septembre 2021

i have an issue with my laravel 5 project i can't find the way to run my project on my local machine

127.0.0.1:8000> [Fri Sep 24 10:46:12 2021] PHP Fatal error: Uncaught ErrorException: file_put_contents(/var/www/html/mpm/storage/framework/views/9573eb5dc606d0d2f327fdda9ed9d4ecfd5f1e97.php): failed to open stream: No such file or directory in C:\xampp\htdocs\amit\mpmnew\mpm20sept2021\mpm\vendor\laravel\framework\src\Illuminate\Filesystem\Filesystem.php:122

this is my error can any one help me with this.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3lYDVSF
via IFTTT

assign multiple category in laravel

this is code use for importing products through csv file to laravel

private function getCategoryIdsFromNames($categories, $subCategory)
{
    $categoryArray = $this->explode($categories);
    if (!$categoryArray)
        return false;
    $categoryIds = [];
    foreach ($categoryArray as $categoryName) {
        $category = CategoryTranslation::query()->where('name', $categoryName)->where('locale', 'en')->first();
        if ($category) {
            $categoryIds[] = $category->category_id;
        } else {
            $newCategory = [
                'name' => $categoryName,
                'is_active' => "1",
                'parent_id' => null,
                'is_searchable' => "1",
            ];
            $category = Category::query()->create($newCategory);
            $categoryIds[] = $category->id;
        }
    }
    return $categoryIds;
}

private function getFinalCategoryIds($categories)
{
    $names = explode('>', $categories);
    $parentCategoryId = null;
    $categoryId = null;
    foreach ($names as $name) {
        $categoryIds = CategoryTranslation::query()->where('name', $name)->where('locale', 'en')->get()->pluck("category_id");
        $categoryId = null;
        if (!empty($categoryIds)) {
            $category = Category::query()->whereIn("id", $categoryIds)->where('parent_id', $parentCategoryId)->first();
            if ($category)
                $categoryId = $parentCategoryId = $category->id;
        }
        if (is_null($categoryId)) {
            $newCategory = [
                'name' => $name,
                'is_active' => "1",
                'parent_id' => $parentCategoryId,
                'is_searchable' => "1",
            ];
            $category = Category::query()->create($newCategory);
            $categoryId = $parentCategoryId = $category->id;
        }
    }
    return [$categoryId];
}

Currently its importing/assigning one category to one product. i want to multiple category import/assign to single product in laravel. divide multiple category by ",". Please any help appreciated .



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3CImGeL
via IFTTT

Call Shopify api in laravel with Particular shopify store data?

  1. shopify public api in laravel Php. Run app to this type error show in laravel 7


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3lQiLG4
via IFTTT

Mysql workbench crash on reverse engineer

I am trying to make ER Diagram of my database but when I go to reverse engineer it crashes. even the wizard works until it reaches Select objects but when I click the execute button.it suddenly crashes.enter image description here it all started when I created a new table in my database.using laravel migrations

Note: it only happens with one database but if I select other database it works fine



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3CAQhXJ
via IFTTT

Laravel firstOrNew based on created_at same date

I am using lumen. I want to use firstOrNew based on created_at. For example in my table there exists data for created_at = 2021-09-23 14:42:13 . For that cases it will update if request date value become that day. Here I tried with

$tableObj = User::firstOrNew([
        'created_at' => Carbon::today() // date('Y-m-d')
    ]);
$tableObj ->mobile= '5457874545';
$tableObj ->save();

Here it always inserted new row. Thanks in advance



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3CyzyEc
via IFTTT

Laravel Maatwebsite how many columns its will accept?

I am doing bulk import using the Laravel Maatwebsite, I Want to Know the how many columns its will accept. Max capability of Maatwebsite excel import.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3Az9EzG
via IFTTT

mercredi 22 septembre 2021

Protect routes in Laravel with angular

I followed this tutorial https://remotestack.io/laravel-angular-jwt-token-based-authentication-example/ and it is working but issue is i'm able to access routes that should be not accessible without login. There is a route user-profile it can be accessed without login but i want it to redirect to login page in case user is not logged in.

api.php

Route::group([
    'middleware' => 'api',
    'prefix' => 'auth'
], function ($router) {
    Route::post('/signup', [JwtAuthController::class, 'register']);
    Route::post('/signin', [JwtAuthController::class, 'login']);
    Route::get('/user', [JwtAuthController::class, 'user']);
    Route::post('/token-refresh', [JwtAuthController::class, 'refresh']);
    Route::post('/signout', [JwtAuthController::class, 'signout']);

    Route::post('/req-password-reset', [ResetPwdReqController::class, 'reqForgotPassword']);
    Route::post('/update-password', [UpdatePwdController::class, 'updatePassword']);
}); 

Any Solution, Thanks



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/39sghrB
via IFTTT

How to pass data from background schedule job to global scope?

I have a background schedule job that doing some code and executing quires that have global scope append to their model and i'm trying to pass data from the job to the global scope like this

job.php

class Job
{

    public static function execute() {

        //Im trying here to find a cleaner and working way better than app()->user_id
        //even it's a bad way, it's also not working
        //because when trying to get the value in UserScope it's always null 
        app()->user_id  = 1;

        app(CreateObjectAction::class)->execute($data);
    }
}   

CreateObjectAction.php

class CreateObjectAction
{

    public function execute(Data $data)
    {
        try {

            DB::beginTransaction();
            
            if (app()->runningInConsole()) {

               //here app()->user_id always is null when the global scope `UserScope` is applied to the query
               //so $exist will be also always empty
               $exist = Object::query()->first();

            } else {
                //....
            }
            
            if(empty($exist)) {

                //here is trying to create an existed object and it gives error
                $object = Object::create(data)->toArray());

            }

            DB::commit();

            return $object;

        } catch (\Throwable $e) {
            DB::rollBack();
            Log::error($e->getTraceAsString());
            return null;
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error($e->getTraceAsString());
            return null;
        }
    }
} 

Object.php

class Object extends Model
{
    use BelongsToUser;
}

BelongsToUser.php

trait BelongsToUser
{
    protected static function BelongsToUser()
    {

        static::addGlobalScope(new UserScope);

    }
}

UserScope.php

class UserScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        if (app()->runningInConsole()) {

                //here app()->user_id always null as well.
                $builder->where("{$model->getTable()}.user_id", "=", app()->user_id); 

        } else {
            //....
        }
    }
}

so please what is the best way that i can pass data from a job running by background worker in console to global scope may thanks in advance for any help



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3AxD7dx
via IFTTT

Missing required parameters for [Route: ] - Laravel 7

I do not get this error on production server which is laravel 5. I did a version upgrade and after I'm getting this error. I don't really know if version upgrade caused this.But I'm getting this error in laravel 7.

Error- Missing required parameters for [Route: ] [URI: users/{user_id}/privacy-groups-modal/{list_id}] [Missing parameters: user_id, list_id]. (View: /opt/lampp/htdocs/php/resources/views/wishlist/show.blade.php)

Web.php

Route::group(['middleware' => ['imageOptimizer', 'auth']], function() {
Route::get('users/{user_id}/privacy-groups-modal/{list_id}', 'UserController@getPrivacyGroupsModel');
});

show.blade.php

reffer the commented

//Error Line: 
var link = ''; 
//Error line
    $(document).on('changed.bs.select', '.privacy-selector', function (e, clickedIndex, newValue, oldValue) {
    
                if (!triggeredByClick)
                    changeTriggered = true;
                var _self = $(this);
                var val = _self.selectpicker('val');
                var prevValue = oldValue;
    
                if ($.isNumeric(val)) {
                    var privacy_level = _self.find('option[value='+val+']').attr('data-type');
                    if (privacy_level == 'custom') {
                        var link = ''; //Error line
                        link = link.replace('list_id', _self.attr('data-list-id'));
    
                        $.ajax({
                            url: link
                        })
                                .done(function(response) {
                                    privacy_group_modal = bootbox.dialog({
                                        title: '@lang("app.my_privacy_groups")',
                                        message: response,
                                        backdrop: false,
                                        animate: false,
                                        buttons: {
                                            cancel: {
                                                label: '@lang("app.cancel")',
                                                className: 'btn-default',
                                                callback: function () {
                                                    privacy_group_modal = null;
                                                    bootbox.hideAll();
                                                    _self.selectpicker('val', prevValue);
                                                    _self.selectpicker('refresh');
                                                }
                                            }
                                        }
                                    });
                                    $('input[type=hidden][name=list_id]').val(_self.attr('data-list-id'));
                                })
                                .fail(function() {
                                    $.toast({
                                        heading: 'Error',
                                        text: '@lang("app.error_occurred")',
                                        showHideTransition: 'slide',
                                        hideAfter: 2000,
                                        position: 'top-center',
                                        icon: 'error',
                                        afterHidden: function () {
                                            _self.selectpicker('val', prevValue);
                                            _self.selectpicker('refresh');
                                        }
                                    });
                                });
    
                    } else {
                        var link = '';
                        link = link.replace('list_id', _self.attr('data-list-id'));
                        link = link.replace('level_id', val);
    
                        $.ajax({
                            url: link,
                        })
                                .done(function() {
                                    $.toast({
                                        heading: 'Success',
                                        text: '@lang("app.successfully_updated")',
                                        showHideTransition: 'slide',
                                        hideAfter: 5000,
                                        position: 'top-center',
                                        icon: 'success'
                                    });
                                })
                                .fail(function() {
                                    $.toast({
                                        heading: 'Error',
                                        text: '@lang("app.error_occurred")',
                                        showHideTransition: 'slide',
                                        hideAfter: 2000,
                                        position: 'top-center',
                                        icon: 'error',
                                        afterHidden: function () {
                                            _self.selectpicker('val', prevValue);
                                            _self.selectpicker('refresh');
                                        }
                                    });
                                });
                    }
                }
    
                if (triggeredByClick)
                    triggeredByClick = false
            });

UserController.php

public function getPrivacyGroupsModel($user_id, $list_id)
    {
        $validator = Validator::make([
                'user_id' => $user_id,
                'list_id' => $list_id
            ], [
                'user_id' => 'required|exists:users,id',
                'list_id' => 'required|exists:wishlists,id',
            ]);

        if ($validator->fails()) {
            return response()->json($validator->errors()->all(), 422);
        }

        $privacy_level_custom = $this->privacy_level_repository
            ->getPrivacyLevelByName('Custom');

        $privacy_groups_of_user = $this->privacy_group_repository
            ->getPrivacyGroupsByUserId((int) $user_id);

        $wishlist = $this->wishlist_repository
            ->getWishlistById((int) $list_id);
        return view()->make('user.partials._privacy-groups-modal', [
                'wishlist' => $wishlist,
                'level_id' => $privacy_level_custom->id,
                'share_with_groups' => $privacy_groups_of_user->where('type', PrivacyGroup::TYPE_SHARE_WITH),
                'unshare_with_groups' => $privacy_groups_of_user->where('type', PrivacyGroup::TYPE_DONT_SHARE_WITH)
            ])
            ->render();
    }

Is this a problem with JQuery syntax after upgrade? Help would be much appreciated



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3CxUkE4
via IFTTT

Dangers of Upgrading from Laravel 5.7.4 to Laravel 8

I would like to know what the possibility is that when I upgrade from Laravel 5.7.4 to Laravel 8 that something in my website will break? If so what would the best approach be to upgrade to the newest version.

Thanks in advance



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3EGPVjX
via IFTTT

How to add new request values to call a function in same controller

How to call a function save(Request $request) from another function in same Controller.

foreach ($_parts as $key => $part_data) {
                $request->item = $part;
                $request->qty = $part_data->quantity;
                $call = $this->save($request);
            }

and my save function is

public function save(Request $request) {
        dd($request->all());
}

the dd($request->all()) returns [].



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3u2S3Oo
via IFTTT

mardi 21 septembre 2021

how to retrieve pivot data from another relationship in API resource

I have 3 models: User, Suburb, City

City hasMany Suburb and Suburb belongsTo a City.

User belongsToMany City and City belongsToMany User.

Suburb belongsToMany User.

There are two pivot tables between these models, and I am using the same API resource User for the response.

class User extends JsonResource
{
   public function toArray($request)
   {
        return 
        [
          'id' => $this->id,
           ........
        ];
   }

}

Now in Suburb page I want to retrieve a field valid_from from City_User pivot table data, So I tried

return [
 'valid_from' => $this->whenPivotLoaded('city_user', function(){
    return $this->pivot->valid_from;
   })
]

However, this returns null as $this->whenPivotLoaded seems point to Suburb-User pivot table not City-User. So this works fine if I navigate to the City page.

I also tried

return [  
 $this->mergeWhen($this->relationLoaded('city'), function () {
                return [
                    'valid_from' => $this->pivot->valid_from,
                ];
            }),]

City-User relation is loaded but still no luck.

dd($this):

App\Http\Resources\User {#900
  +resource: App\User {#837
    #table: "user"
    #guarded: []
    #connection: "mysql"
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
     .....

User Model:

    public function city(): BelongsToMany
    {
        return $this->belongsToMany(City::class, 'city_user')
        ->withPivot('valid_from')
        ;
    }

What I did wrong?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/39tLn22
via IFTTT

lundi 20 septembre 2021

Laravel populate form with cloned model data

I'm implementing a "Clone" button in my application, which should allow to perform the following:

  1. create a copy of the chosen model;
  2. redirect to the create view, whose form field should be populated with the cloned model's data;
  3. allow the user edit some fields;
  4. save the new model.

So far, my ModelController@clone method is:

$newModel = $existingModel->replicate();
$newModel->title = "Copy of ".$existingModel->title;
$newModel->created_at = now() // not sure if necessary, or if it'll be changed once the model is stored in the database

return redirect(route('models.create')); // I know this doesn't do what I need

As it is, obviously, nothing gets passed to the create view, but I can't find any clue on how to do that.

I have tried adding ->withInput(compact($newModel)) to the redirect() call, but I don't see the field being populated.

In the models.create view, I have set up the form field to use the old(...) data, if available.

This answer is almost what I need, but it would imply changing every field to check if there is some sort of input other than the old session data, like this:

<input [other attributes omitted] value="">

Is it the right way to do so, or is there a quicker/more standardized way of proceeding?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3lEvCuZ
via IFTTT

How to check unique validation according to another db column value?

enter image description here

from above table I have to validate regd_no according to to_branch_id. Let's say if I got to_branch_id = 1 then unique will be apply for regd_no but if I got to_branch_id=2 then I need have duplicate values from column to_branch_id = 1 as well as unique if another record is enter in to_branch_id=2.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3kmJDxL
via IFTTT

dimanche 19 septembre 2021

Return Model of Newly created Multiple records

I need to get the model of newly created records

$data = [['name' => 'john'], ['name' => 'Doe']];
$result = Model::insert($data);

But when I checked the $result variable it was Boolean.

How can I get the newly created records?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3ziQtsA
via IFTTT

WHERE and CONCAT columns with Dateformat (Year-month-) and string with Laravel 8

I need the column date and digits to concatenate. The date should be YY-mm format and the digits should have a leading zero.

Example output

21-09-0001

How to do it in WHERE FUNCTION laravel eloquent? like this. I found this on the internet

example:

public function scopeFindDVNumber($query,$name) {
    $query->where(DB::raw(
            "REPLACE(
                    COALESCE(name_first,''),' ',
                    COALESCE(name_middle,''),' ',
                    COALESCE(name_last,'')
                ),
            '  ',' ')"
        ),
    'like', '%' . $name . '%');
}

I don't know how to do it and I need it for search function. Thank you in advance



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3EyaDTf
via IFTTT

samedi 18 septembre 2021

Please help me am beginner in laravel I want to limit number of withdrawal a day

Please help me am beginner in laravel I want to limit number of withdrawal a day...for example I have a project where people requested for payment...I want to limit the number of the people a day where after 10people request it pompt a message that today limit reach please check back tomorrow



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3ClWbMc
via IFTTT

vendredi 17 septembre 2021

Laravel Soft Delete With custom column

i am trying to do softDelete with a custom column, I don't see my trait kicking in, for my case the active column will be used to indicate whether there is a soft delete or not, which be Bool.

<?php

namespace App\Traits;

use App\Scopes\MySoftDeletingScope;

/**
 * @author  
 * Trait MySoftDelete
 * @package App\Traits
 */
trait SoftDelete
{
    /**
     * Indicates if the model is currently force deleting.
     *
     * @var bool
     */
    protected $forceDeleting = false;

    /**
     * Boot the soft deleting trait for a model.
     *
     * @return void
     * @author  
     */
    public static function bootSoftDeletes()
    {
        static::addGlobalScope(new MySoftDeletingScope());
    }

    /**
     * Force a hard delete on a soft deleted model.
     *
     * @return bool|null
     * @author  
     */
    public function forceDelete()
    {
        $this->forceDeleting = true;

        $deleted = $this->delete();

        $this->forceDeleting = false;

        return $deleted;
    }

    /**
     * Perform the actual delete query on this model instance.
     *
     * @return mixed
     * @author  
     */
    protected function performDeleteOnModel()
    {
        if ($this->forceDeleting) {
            return $this->newQueryWithoutScopes()->where($this->getKeyName(), $this->getKey())->forceDelete();
        }

        return $this->runSoftDelete();
    }

    /**
     * Perform the actual delete query on this model instance.
     *
     * @return void
     * @author  
     */
    protected function runSoftDelete()
    {
        $query = $this->newQueryWithoutScopes()->where($this->getKeyName(), $this->getKey());

        $this->{$this->getActiveColumn()} = false;

        $query->update(['active' => false]);
    }

    /**
     * Restore a soft-deleted model instance.
     *
     * @return bool|null
     * @author  
     */
    public function restore()
    {
        // If the restoring event does not return false, we will proceed with this
        // restore operation. Otherwise, we bail out so the developer will stop
        // the restore totally. We will clear the deleted timestamp and save.
        if ($this->fireModelEvent('restoring') === false) {
            return false;
        }

        $this->{$this->getActiveColumn()} = true;

        // Once we have saved the model, we will fire the "restored" event so this
        // developer will do anything they need to after a restore operation is
        // totally finished. Then we will return the result of the save call.
        $this->exists = true;

        $result = $this->save();

        $this->fireModelEvent('restored', false);

        return $result;
    }

    /**
     * Determine if the model instance has been soft-deleted.
     *
     * @return bool
     * @author  
     */
    public function trashed()
    {
        return  !($this->{$this->getActiveColumn()});
    }

    /**
     * Register a restoring model event with the dispatcher.
     *
     * @param  \Closure|string  $callback
     * @return void
     * @author  
     */
    public static function restoring($callback)
    {
        static::registerModelEvent('restoring', $callback);
    }

    /**
     * Register a restored model event with the dispatcher.
     *
     * @param  \Closure|string  $callback
     * @return void
     * @author  
     */
    public static function restored($callback)
    {
        static::registerModelEvent('restored', $callback);
    }

    /**
     * Determine if the model is currently force deleting.
     *
     * @return bool
     * @author  
     */
    public function isForceDeleting()
    {
        return $this->forceDeleting;
    }

    /**
     * Get the name of the "deleted at" column.
     *
     * @return string
     * @author  
     */
    public function getActiveColumn()
    {
        return defined('static::ACTIVE') ? static::ACTIVE : 'active';
    }

    /**
     * Get the fully qualified "deleted at" column.
     *
     * @return string
     * @author  
     */
    public function getQualifiedActiveColumn()
    {
        return $this->getTable().'.'.$this->getActiveColumn();
    }
}


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3lxsIIw
via IFTTT

jeudi 16 septembre 2021

Getting 302 found in ajax jquery request in laravel

I'm using ajax request in laravel and passing csrf token also but some times my application gets stuck and getting this error :

enter image description here

Code :

  var formData = $(this).serialize();
    $.ajaxSetup({
        header:$('meta[name="_token"]').attr('content')
    });
    $.ajax({
        url:$(this).attr('action'),
        type:'POST',
        data:formData,
        headers: {
            Accept: "application/json"
        },
        success:function(response) {

This form is in modal popup :

 <form id="user-login" class="login" action="" method="post">
 

Any solution, Thanks



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3Cj68Kj
via IFTTT

I need some dynamic form that contain tables inside it in web development

I want the user to create dynamic form that contain a table for input data to database and the table needs to be created as user needs automatically on database. Any help



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3lxAl1g
via IFTTT

mercredi 15 septembre 2021

how to fix error Trying to access array offset on value of type null in laravel

i know this question is asked but my scenario is different my array is

  $data = array(
            'merchantId'        => $merchantId,
            'qrCode'            => $qrCode,
     );

in next step i am calling jeson data and api

    $json_data = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $signed_data = $data;
    $signed_data['sign'] = Encryption::generateSignature($json_data,storage_path().self::MERCHANT_PRIVATE_KEY);

but i get this error

 public static function verifySignature(string $data, string $key)

{

    $data = json_decode($data, true, 512, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

    $signature = $data['sign']; //here i get error on this line with Trying to access array offset on value of type null

can some one help me to fiure it out i never integrate api so i dont know this error



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/39bsHnS
via IFTTT

how to apply filter on pivot table??facing some issue

Model of Category

public function lists(){
        return $this->belongsToMany(listing::class);
    }

Model of Listing

public function categories(){
    return $this->belongsToMany(Category::class)->withPivot(['category_id','listing_id']); }

Controller: when i die dumb this query then i get all lists that is in listings table but i just want to get those lists whose have these categories

 if($request->categories){
            $var=$request->categories;//data in array 1,2,3
            $lists =Listing::with(['categories' => function ($query) use($var)  {
                $query->whereIn('category_id',['=',$var]);

            }])->get();
            dd($lists);//


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3EmNP8J
via IFTTT

uncheck a checkbox when I check another - laravel

i have a problem, i need to uncheck a checkbox when check another checkbox. but checkboxes must not have the same name. the name field must be different.

       <input type="radio" class="new-control-input" name="custom-radio-1">

  <input type="radio" class="new-control-input" name="custom-radio-2">

How can I make them uncheck?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3AfKBlh
via IFTTT

500 Whoops, something went wrong on our servers. (Laravel) [closed]

my laravel log shows this please help me fix this i tried everything online but nothing works

[2021-09-15 20:55:29] production.ERROR: SQLSTATE[HY000] [2002] Connection refused (SQL: select * from `settings` limit 1) {"exception":"[object] (Illuminate\\Database\\QueryException(code: 2002): SQLSTATE[HY000] [2002] Connection refused (SQL: select * from `settings` limit 1) at /home/vol2_3/byethost32.com/b32_29729239/htdocs/cronlab/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664, PDOException(code: 2002): SQLSTATE[HY000] [2002] Connection refused at /home/vol2_3/byethost32.com/b32_29729239/htdocs/cronlab/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70)
[stacktrace]

my .env file has my details related to my database correctly but still problem remains domain link is:http://verux.byethost32.com/



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2XtmbX1
via IFTTT

Model create returns object without ID

I'm doing this:

$item = Item::create(["name"=>"Hello"]);
dd($item->id);

Displays null;



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3nOyZCr
via IFTTT

Communicate from micro-service to main application

So I am looking for some solutions. Here is my scenario. I have a web application which is developed in Laravel 5.5 on the back-end and Angular 1.4 on the front end. Also, I have a micro-service in Go Lang. Now what happens is that there is some data that needs to be processed in the micro-service. What I do is send that set of data to RabbitMQ from where the micro-service picks that data and processes it and then stores it in MongoDB. Then the main application, when required, accesses MongoDB and retrieves the data. Now what I want to do is I want to track live the progress of the data processing being done on micro-service side. How micro-service processes the data is that it takes the data set from RabbitMQ and then loops through it and processes it one by one. So what I want is for main application to know whenever on single data item gets processed.

Solution Tried: I have tried Pusher for it in which I send notification after one data item gets processed and then count number of notifications but that doesn't work as the event gets subscribed more than once and the count gets messed up.

Other solution in my mind is to use RabbitMQ again but how would I use it bearing in mind that I have front end of the main application in Angular. I can read the RabbitMQ in Laravel but how'd I send that information to front-end?

Any other solutions?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3ltMRPo
via IFTTT

ip undefined on some system [closed]

I'm getting ip using this php code

  $ip="";
        if (!empty($_SERVER['HTTP_CLIENT_IP']))
        {
          $ip=$_SERVER['HTTP_CLIENT_IP'];
        }
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
          $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        else if(!empty($_SERVER['HTTP_FORWARDED_FOR']))
        {
          $ip=$_SERVER['HTTP_FORWARDED_FOR'];
        }
        else if(!empty($_SERVER['HTTP_FORWARDED']))
        {
          $ip=$_SERVER['HTTP_FORWARDED'];
        }
        else if(!empty($_SERVER['REMOTE_ADDR']))
        {
          $ip=$_SERVER['REMOTE_ADDR'];
        }
        else
        {
           $ip="Unknown";
        }

but on some system i'm not getting any ip,

Any suggestion Thanks



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3EklAaH
via IFTTT

mardi 14 septembre 2021

Laravel Nova Image Collection upload "The image-collection must be an image"

I've inherited an Expo app with a Laravel backend, and I'm having trouble allowing images to be uploaded on the Nova admin panel. Whenever I try to upload a photo, I get an error that says "The image-collection must be an image." From the code, I can tell the name of the image collection is "image-collection", but I'm not sure why Nova thinks the image collection isn't an image. I'm able to upload photos through the app, so it looks like it should be a Nova issue. Here's a screenshot of the error I'm getting: Laravel Nova Image Upload error

Here is the Image model that we are using to store the images in the database

<?php

namespace App;

use App\Traits\Searchable;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;

use Spatie\MediaLibrary\HasMedia\HasMedia;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
use Spatie\MediaLibrary\Models\Media;

/**
 * App\Image
 *
 * @property int $id
 * @property int $restaurant_id
 * @property string|null $image_path
 * @property string|null $caption
 * @property string $slug
 * @property bool $active
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property-read mixed $slug_title
 * @property-read \Illuminate\Database\Eloquent\Collection|\Spatie\MediaLibrary\Models\Media[] $media
 * @property-read \App\Restaurant $restaurant
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Image findSimilarSlugs($attribute, $config, $slug)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Image newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Image newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Image query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Image whereActive($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Image whereCaption($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Image whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Image whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Image whereImagePath($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Image whereRestaurantId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Image whereSlug($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Image whereUpdatedAt($value)
 * @mixin \Eloquent
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Image searchBy($value)
 */
class Image extends Model implements HasMedia
{
    use Sluggable;
    use HasMediaTrait;
    use Searchable;

    public function sluggable()
    {
        return [
            'slug' => [
                'source' => 'slug_title',
                'unique' => true,
            ]
        ];
    }

    protected $fillable = [
        'caption', 'active', 'review_id'
    ];

    protected $searchable = [
        'id', 'caption',
    ];

    protected $casts = [
        'active' => 'boolean'
    ];

    public function getSlugTitleAttribute()
    {
        return Str::random(12);
    }

    public function restaurant()
    {
        return $this->belongsTo(Restaurant::class);
    }

    public function registerMediaConversions(Media $media = null)
    {
        $this->addMediaConversion('thumb')
//            ->width(130)
            ->height(300)
            ->withResponsiveImages();
    }

    public function registerMediaCollections()
    {
        $this->addMediaCollection('main-image')->singleFile();
        $this->addMediaCollection('image-collection');
    }
}

Here is the corresponding Nova panel:


namespace App\Nova;

use Laravel\Nova\Fields\BelongsTo;
use Laravel\Nova\Fields\ID;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Fields\Boolean;
use Laravel\Nova\Fields\Markdown;
use Laravel\Nova\Http\Requests\NovaRequest;
use Ebess\AdvancedNovaMediaLibrary\Fields\Images;

class Image extends Resource
{
    /**
     * The model the resource corresponds to.
     *
     * @var string
     */
    public static $model = 'App\Image';

    /**
     * The single value that should be used to represent the resource when being displayed.
     *
     * @var string
     */
    public static $title = 'caption';

    /**
     * The columns that should be searched.
     *
     * @var array
     */
    public static $search = [
        'caption'
    ];

    /**
     * Get the fields displayed by the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function fields(Request $request)
    {
        return [

            BelongsTo::make('Restaurant Name', 'restaurant', 'App\Nova\Restaurant')->creationRules('required')->sortable(),
            Text::make('Caption')->rules('required', 'max:84')->sortable(),

            // allow batch image upload
            Images::make('Image Collection', 'image-collection') // second parameter is the media collection name
                //->withResponsiveImages()
                ->customPropertiesFields([
                    Boolean::make('Active'),
                    Markdown::make('Description'),
                ])
                ->setFileName(function($originalFilename, $extension, $model){
                    return md5($originalFilename) . '.' . $extension;
                })
                ->conversionOnPreview('thumb') // conversion used to display the "original" image
                ->conversionOnDetailView('thumb') // conversion used on the model's view
                ->conversionOnIndexView('thumb') // conversion used to display the image on the model's index page
                ->conversionOnForm('thumb') // conversion used to display the image on the model's form
                ->fullSize() // full size column
                //->rules('required') // validation rules for the collection of images
                // validation rules for the collection of images
                ->singleImageRules('dimensions:min_width=100'),

            Boolean::make('Active'),
        ];
    }

    /**
     * Get the cards available for the request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function cards(Request $request)
    {
        return [];
    }

    /**
     * Get the filters available for the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function filters(Request $request)
    {
        return [];
    }

    /**
     * Get the lenses available for the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function lenses(Request $request)
    {
        return [];
    }

    /**
     * Get the actions available for the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function actions(Request $request)
    {
        return [];
    }
}

Any help on this would be much appreciated, as I am a Laravel and Laravel Nova beginner.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3tFF4BT
via IFTTT

How prevent slashes on URL during json_encode() - PHP? [duplicate]

I'm trying to construct a clean json with no slashes, but I kept getting them. I've been creating array, and encode it like so json_encode($data); all the time. It always works, but this time I got a lot slashes.

$data                                = [];
$data['input']['upload-destination'] = env('CONTROLLER_URL').'/controller/v1/'.$nodeId.'/pkt_capture/upload?port='.$interface;
$data['input']['upload-username']    = 'code-ro@site.com';
$data['input']['upload-password']    = '123';

$url           = $SERVICE_URL.'/restconf/data/interfaces-state/interface=0%2F'.$interface.'/packet-capture-start';
$data          = json_encode($data);
$result        = HTTP::post($url, $data);


//dd(get_defined_vars());

enter image description here

How do I avoid that ?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3lgDGBW
via IFTTT

how to roll back Laravel command

I have run following Laravel command php artisan make:migration add_category_id_to_posts but I need run following command as well php artisan make:migration add_category_id_to_posts --table=posts then I need roll back first command and run second command. then How?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3kb4qoe
via IFTTT

How to use loop for following Laravel code?

    $query1 =  User::where('sponser_id',$_SESSION['ruserid'])->get('userid');
    $count1= count($query1);
    
    $query2 =  User::whereIn('sponser_id',$query1)->get('userid');
    $count2= count($query2);

    $query3 =  User::whereIn('sponser_id',$query2)->get('userid');
    $count3= count($query3);

    $query4 =  User::whereIn('sponser_id',$query3)->get('userid');
    $count4= count($query4);

    $query5 =  User::whereIn('sponser_id',$query4)->get('userid');
    $count5= count($query5);

    $query6 =  User::whereIn('sponser_id',$query5)->get('userid');
    $count6= count($query6);

    $query7 =  User::whereIn('sponser_id',$query6)->get('userid');
    $count7= count($query7);

    $allcount=$count1+$count2+$count3+$count4+$count5+$count6+$count7;

I want to calculate the total downlines of users. This code works fine. But How to simplifies this code using a loop?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3tEcukk
via IFTTT

lundi 13 septembre 2021

Save input value in session and then print variable

is it possible to pass the value of an input with session? i need to pass the value 25 and then save to session

Ej:

Blade.php:

 <input type="hidden" name="idevento" value="25">

Controller:

 session(['variableName' => $request->input("idevento")]);

Then I get the value with:

$save_value = Session::get('variableName');

the problem is that it does not save the value, help pls



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3k9sTtU
via IFTTT

I get the same row duplicated as the result when I do a simple join using the laravel's DB facade

Code

$result = DB::table('disaster_rescue_data')
    ->join('users', 'disaster_rescue_data.username', '=', 'users.email')
    ->get();

Problem

I have this very simple join as mentioned in the above code. However when I render the data on a view or dd the $result, I get the same row duplicated and I can not figure out why. (The rows contain the same data.)

(I am using Laravel 5.4)

Can someone please help me figure out why? (I tried different techniques and none of them worked! Thanks.)



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3nsU3xW
via IFTTT

How to solve attachement/storage problem in Freescout

I have problems uploading attachements to outgoing messages in Freescout. I get the following error in the logs: Impossible to create the root directory "/var/www...{"userId":1,"email":"XXX","exception":"[object] (League\Flysystem\Exception(code: 0): Impossible to create the root directory "/var/www/.../httpdocs/XX/storage/app/attachment/1/7/1". at /var/www/vhosts/.../httpdocs/XX/vendor/league/flysystem/src/Adapter/Local.php:106)

According to the following link there is an explanation how to configure the webserver so that the application can update itself, which seems to be the problem.

https://github.com/freescout-helpdesk/freescout/wiki/Installation-Guide#6-configuring-web-server

In the system status I get the message that there are non-writeable files in my ....storage/framework/cache/data/.... section. The system tells me to run the following command:

chown -R www-data:www-data /var/www/vhosts/domain/httpdocs/installation-folder

However, after running that command, Freescout could not be reached anymore and I just get a blank screen when trying to open the application.

I also tried to update the directory/file permissions for the storage-folder and sub-folders manually to 775 but some files and directories remain unchanged at 755.

Any ideas what I am doing wrong or what can be done to solve this issue?

Thank you.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3Ehep32
via IFTTT

URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings bin laravel; Socialite

I'm using socialite for facebook login but i'm getting this error enter image description here

In services.php i have

   'facebook' => [
        'client_id' => 'XXXXXXXXXX',
        'client_secret' => 'XXXXXXXXXXXXXXX',
        'redirect' => 'https://XXXXXXXXXXX.in/auth/facebook/callback',
    ],

Same i have in site url :

https://XXXXXXX.in/

In Valid OAuth Redirect URIs :

https://XXXXXXX.in/auth/facebook/callback

Any Solution Please,Thanks



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2YInodm
via IFTTT

Laravel 5 bearer token authentication

How do I get the bearer token that I passed from Postman in a Laravel 5 controller? I am executing the following code:

$request = request(); 
$token = $request->bearerToken();
echo $token;

Nothing is printed.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3k4zC8h
via IFTTT

upload an file with laravel and VueJS causes error

I am using Laravel 7 for my project. Although I am using VueJS within Laravel. When I try to upload an image, I get the error (419 | page expired) immediately after submitting the form!. But in the console window, I can confirm that the token is there....

This is my blade file:

<html>
<head>
  <meta name="csrf-token" content="">
  <title>app</title>
  <script>
    (function(){
      window.Laravel = {
        csrfToken: ''
      };
    })();
  </script>   
</head>
<body>
  <div id="vueapp">
    <admin></admin>
  </div>
<script src=""></script>
</script>
</body>
</html>

This is my .vue file:

<template>
  <div>
    <div class="form-group">
      <label for="exampleInputFile">img</label>
      <form class="input-group" action="/app/upload" method="post" :headers="{'x-csrf-token': token}">
        <div class="custom-file">
          <input type="file" class="custom-file-input" id="exampleInputFile">
          <label class="custom-file-label" for="exampleInputFile">choose file</label>
        </div>
        <div class="input-group-append">
          <button class="input-group-text" action="app/upload">uplaod</button>
        </div>
      </form>
    </div>
  </div>
</template>
<script>
export default{
  data(){
    return{
    token: ''
    }
  },
  methods: {
  },
  async created(){
    const res = await this.callApi('get','app/get_categories')
    this.token = window.Laravel.csrfToken
    this.categories = res.data
  }
}
</script>

I also tried to included some parameters :

name="_token" v-bind:value="csrf"
name="_token" :value="token"

and to clear cache using:

php artisan view:clear 
php artisan route:clear 
php artisan cache:clear
php artisan config:cache

and to change my .env variable APP_NAME to unique name

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

my controller :

public function upload(Request $request){
        $image = time().'.'.$request->file->extension();
        $request->file->move(public_path('uploads'),$image);
        return $image;
    }


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3k4fQd6
via IFTTT

dimanche 12 septembre 2021

How to feature test more complicated cases on Laravel using PHPUnit

I'm using Laravel for my project and I'm new to unit/feature testing so I was wondering what is the best way to approach more complicated feature cases when writing tests?

Let's take this test example:

  public function testSucceedIfConnectAuthorised()
  {
    $connection = factory(Connection::class)->make([
      'sender_id'     => 1,
      'receiver_id'   => 2,
      'accepted'      => false,
      'connection_id' => 5,
    ]);

    $user = factory(User::class)->make([
      'id' => 1,
    ]);

    $response = $this->actingAs($user)->post(
      '/app/connection-request/accept',
      [
        'accept'     => true,
        'request_id' => $connection->id,
      ]
    );

    $response->assertLocation('/')->assertStatus(200);
  }

So we've got this situation where we have some connection system between two users. There is a Connection entry in the DB created by one of the users. Now to make it a successful connection the second user has to approve it. The problem is within the UserController accepting this through connectionRequest:

  // TalentController
  public function connectionRequest(Request $request)
  {
    // we check if the user isn't trying to accept the connection
    // that he initiated himself
    $connection = $this->repository->GetConnectionById($request->get('request_id'));
    $receiver_id = $connection->receiver_id;
    $current_user_id = auth()->user()->id;

    if ($receiver_id !== $current_user_id) {
      abort(403);
    }

    [...]
  }


  // UserRepository 
  public function GetConnectionById($id)
  {
    return Connection::where('id', $id)->first();
  }

So we've got this fake (factory created) connection in the test function and then we unfortunately are using its fake id to run a check within the real DB among real connections, which is not what we want :(

Researching I found an idea of creating interfaces so then we can provide a different method bodies depending if we're testing or not. Like here for GetConnectionById() making it easy to fake answers to for the testing case. And that seems OK, but:

  • for one it looks like a kind of overhead, besides writing tests I have to make the "real" code more complicated itself for the sole purpose of testing.
  • and second thing, I read all that Laravel documentation has to say about testing, and there is no one place where they mention using of interfaces, so that makes me wonder too if that's the only way and the best way of solving this problem.


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3k3Qufx
via IFTTT

Check unique email with password not null in laravel

I have a user table where there are two fields email and password

 $validator = Validator::make($request->all(),[
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:5', 'confirmed','min:8'],
            'password_confirmation' => ['min:8']
        ]);

I'm using unique field to check whether email is unique but i want to show message user already exist only if email already exist and password field not null, because i have a case if user is login through social media account then password is not saved and is null, so when user is trying to register through normal account then i want to update user fields.

Any Suggestion Thanks



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3A4maHh
via IFTTT

samedi 11 septembre 2021

150 "Foreign key constraint is incorrectly formed"

I have a problem with migrating my table.

I have a users table that has a string id and the table was created before with SQL without a migration.

Later on, I created a table called surveys that has a foreign key to user_id with the following code .

hema::create('surveys', function (Blueprint $table) {
            $table->increments('id');
            $table->string('user_id',40);
            $table->foreign('user_id')->references('id')->on('users') ->onUpdate('cascade')->onDelete('cascade');
            $table->string('gender');
            $table->string('age');
            $table->string('education');
            $table->string('proficiency');
            $table->string('behaviour');
            $table->timestamps();
        });

I am always getting the below error whenever I try to migrate it and I have no clue why is this happening. The id in table users is varchar 40 and so is the user_id.


  SQLSTATE[HY000]: General error: 1005 Can't create table `d0372341`.`surveys` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `surveys` add constraint `surveys_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade on update cascade)

  at D:\xampp install\htdocs\game-db\vendor\laravel\framework\src\Illuminate\Database\Connection.php:692
    688▕         // If an exception occurs when attempting to run a query, we'll format the error
    689▕         // message to include the bindings with SQL, which will make this exception a
    690▕         // lot more helpful to the developer instead of just the database's errors.
    691▕         catch (Exception $e) {
  ➜ 692▕             throw new QueryException(
    693▕                 $query, $this->prepareBindings($bindings), $e
    694▕             );
    695▕         }
    696▕     }

So if you can please help me with this I would really appreciate it.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3k1Jn7i
via IFTTT

vendredi 10 septembre 2021

Laravel Mail - InvalidArgumentException with message 'No connector for []'

I'm on Laravel 5.1, I configured my mail as described here https://laravel.com/docs/5.1/mail, and every config (config/mail.php, config/services.php) appears when I test from tinker. (eg: config('mail.driver'), etc)

But when I ran this from tinker

use Mail;
Mail::raw('Test mail from Tinker', function($msg) {$msg->to('my-mail@gmail.com')->subject('Test Email'); });

I got this one single line exception

InvalidArgumentException with message 'No connector for []'

Any idea what could be the issue ?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3Easdwc
via IFTTT

Auth + login not work after composer update

I have an issue with old version of Laravel 5.5 after composer update.

I can't login to dashboard anyway and didn`t get an error ,I trust there is no issues with username and password

what can I do to fix this issue

here is composer.json

{
"name": "laravel/laravel",   
"type": "project",
"require": {
    "php": ">=7.0.0",
    "fideloper/proxy": "~3.3",
    "guzzlehttp/guzzle": "^6.5",
    "intervention/image": "^2.4",
    "jrm2k6/cloudder": "0.4.*",
    "laravel/framework": "5.5.*",
    "laravel/passport": "~4.0",
    "laravel/tinker": "~1.0",
    "laravelcollective/html": "^5.4.0",
    "maatwebsite/excel": "~2.1.0",
    "paragonie/random_compat": "2.*",
    "phpseclib/phpseclib": "~2.0",
    "ultraware/roles": "^5.5"
},
"require-dev": {
    "filp/whoops": "~2.0",
    "fzaninotto/faker": "~1.4",
    "mockery/mockery": "~1.0",
    "phpunit/phpunit": "~6.0",
    "symfony/thanks": "^1.0"
},
"autoload": {
    "classmap": [
        "database/seeds",
        "database/factories"
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files":[
        "app/helper/images.php"
    ] 
},
"autoload-dev": {
    "psr-4": {
        "Tests\\": "tests/"
    }
},
"extra": {
    "laravel": {
        "dont-discover": [
        "laravel/passport"
        ]
    }
},
    

}

waiting your kindly reply thanks



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3tyK2QF
via IFTTT

How to catch SSH command output contain sub string ? - Laravel 5.8

I'm trying to catch the output of the command and throw error/success accordingly.

$resultFromServer = []; 
SSH::run($command, function($line)
{
    echo $line.PHP_EOL;

    if($line!= null) {
        array_push($resultFromServer, $line); // crash 
    }
});

dd($resultFromServer);

Check out my output

WARNING: Kubernetes configuration file is group-readable. This is insecure. Location: /root/.kube/config WARNING: Kubernetes configuration file is world-readable. This is insecure. Location: /root/.kube/config Error: open test.yaml: no such file or directory

[]

I'm trying to look for this string Error: and whatever to the right of it, I will display in my alert message.

Error: open test.yaml: no such file or directory

I'm trying

to store each line into an array and loop through and check for string contain, but I can't even store it into the array.

I kept getting a crash - if - I uncomment that line

enter image description here

How do I prevent the crash ? Do I need to add some sleep() ?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2X8tT8s
via IFTTT

SSH into dynamic remote server and run a command - Laravel 5.8

I'm using L 5.8 and I have a form with 3 inputs

enter image description here

Right now, I can SSH into a specific server with this package laravelcollective/remote": "~5.8. I required to pre configured IP, UN, PW in the config/remote.php like so :

'connections' => [
    'production' => [
        'host'      => '1.1.1.1',
        'username'  => 'code',
        'password'  => '8888',
        'key'       => '',
        'keytext'   => '',
        'keyphrase' => '',
        'agent'     => '',
        'timeout'   => 10,
    ],
],

Then, I can easily run any command(s) or even chain them

$commands = ['cd /home/code && ./runMe.sh'];
SSH::run($commands, function($line)
{
    echo $line.PHP_EOL;
});

Result

My portal will connect to that server and run that command successfully, and I've verified it.


Now

I need to read it from form inputs. Is it possible to use the same plugin and dynamically setting that file remote.php ?

or

Should I start looking into something else because this is a dead end ?

Please advise,



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2XcJswo
via IFTTT

Cannot get user to select account before login using facebook socialite

I'm using socialite for facebook login but the issue is if i'm already login in facebook account then before login it should force user to select pop up this code is working for google login but i want it in facebook login also which is not working.

public function facebookRedirect()
    {
        return Socialite::driver('facebook')->with(["prompt" => "select_account"])->redirect();
    }

Any suggestions. Thanks



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2X6OsSI
via IFTTT

jeudi 9 septembre 2021

Getting issue after composer update

I am trying to update composer but getting the below error

 Problem 1
    - Root composer.json requires yajra/laravel-datatables-oracle dev-develop, it is found yajra/laravel-datatables-oracle[dev-develop] in the lock file and yajra/laravel-datatables-oracle[dev-closure-di, dev-master, dev-L4, dev-L5-DT1.9, 1.3.0, ..., v1.5.0, v2.0.0, ..., v2.2.2, v3.0.0, ..., v3.6.13, v4.0.0, ..., v4.3.3, v5.0.0-beta, ..., v5.12.5, v6.0.0-alpha, ..., v6.29.3, v7.0.0, ..., v7.10.3, v8.0.0, ..., v8.13.7, v9.0.0, ..., v9.18.1] from composer repo (https://repo.packagist.org) but these do not match your constraint and are therefore not installable. Make sure you either fix the constraint or avoid updating this package to keep the one from the lock file.

My laravel version 5.5

I try below command but nothing happened

composer require yajra/laravel-datatables-oracle:"~8.0"
composer self-update --stable
composer self-update --1

I dont know why this happen anyone have idea then please let me know



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2YHHLHN
via IFTTT

How do I redirect my login link to show the landing page when someone logs into his account

I have two login links that appears on the navbar and the other one appears when a user clicks on the checkout button. I.ve configured the links at the logincontroller for the checkout page to be like this.

 protected function authenticated(Request $request, $user)
{           if(Auth::user()->userType == 'admin'){
            return redirect('/admin')->with('status','Welcome');
        }else{
            return redirect()->back()->with('status','Welcome');
        }
}.

As you can see, when the user is at the checkout page and manages to login to his account, he gets redirected to the same checkout page.I want the other login link to redirect the users to the landing page, but the users are redirected to the home page as shown in the url.

How can I change this a redirect them to the landing page which is 'http://127.0.0.1:8000.' If you're an expert with laravel, can you assist? It's an ecommerce application.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/38QrQsf
via IFTTT

read string by white spaces in php

i an trying to read a PDF with this library \Smalot\PdfParser\Parser(); in laravel 5.6

I am getting all content ok, but i have this:

Array
(
    [0] =>  MARTIN CARRILLO MARIA ESMERALDA ALHAMBRA 10 958 54 38 93
    [1] =>  ESPIGARES DIAS JOSE ANTONIO ALHAMBRA 11 958 54 33 32
    [2] =>  GUTIERREZ TITOS JOSE MANUEL ALHAMBRA 12 958 54 04 10
    [3] =>  MARTIN COBOS ANTONIO ALHAMBRA 18 958 54 33 28
    [4] =>  GOMEZ CARRILLO JOSE ALHAMBRA 20 958 54 32 72
    [5] =>  RODRIGUEZ RUANO BUENAVENTURA ALHAMBRA 21 958 54 35 86
    [6] =>  GARCIA ARIAS MARIA ISABEL ALHAMBRA 22 958 54 07 87
    [7] =>  RODRIGUEZ JIMENEZ MIGUEL ALHAMBRA 27 958 54 08 77
    [8] =>  GUTIERREZ FERNANDEZ AMANDA HILDA ALHAMBRA 3 958 49 98 62
    [9] =>  DIAZ FLORIAN DOLORES ALHAMBRA 30 958 54 33 99
    [10] =>  PEREZ LASTRA SAUL ADAN ALHAMBRA 32 958 54 31 46
    [11] =>  AMIGO MOLINA MARIA MATILDE ALHAMBRA 35 958 54 31 91
    [12] =>  ESPIGARES GOMEZ JORGE ALHAMBRA 37 958 54 02 22
    [13] =>  ESPIGARES ESPIGARES JOSE ALHAMBRA 40 958 54 31 83

but I need to get the second surname, surname, name, address and phone from these strings... I think that I can get all data count white spaces.

I am trying this:

// loop to get data line
foreach($dataByLine as &$line){      
    // delete first element in string
    $cleanString = substr($line, 0, 7);
    $line = str_replace($cleanString, "", $line);   
    
    $line = preg_replace('/^[\d]+/','',$line);
    //$line = ltrim($line,"0123456789");
    $stringDivide = preg_split('/\s+/', $line, -1, PREG_SPLIT_NO_EMPTY);

    
    //array_push($secondSurnameArray, $stringDivide[0]);

    array_push($dataList, $line);
}

print_r($dataList);

but this return:

Array
(
    [0] => MARTIN
    [1] => CARRILLO
    [2] => MARIA
    [3] => ESMERALDA
    [4] => ALHAMBRA
    [5] => 10
    [6] => 958
    [7] => 54
    [8] => 38
    [9] => 93
)
Array
(
    [0] => ESPIGARES
    [1] => DIAS
    [2] => JOSE
    [3] => ANTONIO
    [4] => ALHAMBRA
    [5] => 11
    [6] => 958
    [7] => 54
    [8] => 33
    [9] => 32
)
Array
(
    [0] => GUTIERREZ
    [1] => TITOS
    [2] => JOSE
    [3] => MANUEL
    [4] => ALHAMBRA
    [5] => 12
    [6] => 958
    [7] => 54
    [8] => 04
    [9] => 10
)

for example, but if i do this:

array_push($secondSurnameArray, $stringDivide[0]);

this return that index 0 it´s not defined.

I need this data to create one array to create insert query.

Thanks for help me, read me and sorry for my english.

update

i hope this:

$secondSurname = ['MARTIN', 'ESPIGARES', 'GUTIERREZ'....etc]
$surname = ['CARRILLO', 'DIAS', 'TITOS', .....etc]
$name = ['JOSE', 'JOSE', 'ANTONIO']
$addres = ['ALHAMBRA 10', 'ALHAMBRA 11', 'ALHAMBRA 12', etc]
$phone = ['958 54 38 93', '958 54 33 32', '958 54 04 10']

after i need to do array merge with $secondSurname, $surname and $name to do insert query



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3hgFNEI
via IFTTT

login through specific guard using socialite in laravel

I have this function for google login

function :

  public function loginWithGoogle()
    { 
        try {
            $googleUser = Socialite::driver('google')->user();
            $user = User::where('google_id', $googleUser->id)->first();

            if($user){
                Auth::login($user);
                return redirect('/home');
            }

            else{
                $createUser = User::create([
                    'name' => $googleUser->name,
                    'email' => $googleUser->email,
                    'google_id' => $googleUser->id,
                    'password' => encrypt('test@123')
                ]);

                Auth::login($createUser);
                return redirect('/home');
            }

        } catch (Exception $exception) {
            dd($exception);
        }
    }

but i have created a specific guard for user login :

   'user' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

how i will change the guard to user when i login in the application through socialite Any suggestion Thanks.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3yXx3JJ
via IFTTT

How to set up locale and redirection logic Laravel 5

I'm new to laravel and looking for advice on how to structurally set up some functionality.

My application uses the ipInfo api to identify the visitors country via ip, then redirects the user to the appropriate locale (e.g. /gb/, /ca/ etc...).

I only want to make a single call to ipInfo per request, but since the visitor is redirected, I'm struggling to cut the calls down to one (from two).

Initially, I had the logic within a serviceprovider boot method, but I decided using session variables was a good idea for keeping track of the visitor - and since sessions are not (normally) available in a service provider, I moved the logic to custom middleware.

This middleware is called after sessionStart middleware and for the most part works well. However, I've now noticed that this middleware is not being triggered for every request which I think may have something to do with caching? This means that the locale redirect logic is not always triggered and the user is sometimes not redirected.

This must be a normal feature in many laravel applications, so how should this be done? Bear in mind that I want the redirection/locale logic to remain as fast as possible, so I don't want this logic to occur within a view.

*Side-note, I'm using statamic as a framework on top of laravel 5.

Thanks!

public function handle($request, Closure $next)
{
    $uri = $request->server->get('REQUEST_URI');

    if (
        env('APP_ENV') != 'dev' &&
        request()->server->get('REQUEST_METHOD') === 'GET' &&
        !in_array('img', request()->segments()) && 
        !in_array('_debugbar', request()->segments())) {

            if (!Session::has('from_redirect')) {
                $user_real_country = $this->getUserCountry();
                Session::put('user_country', $user_real_country);
            } else {
                $user_real_country = Session::get('user_country');
                Session::forget('from_redirect');
                Session::save();
            }

            if (Request::input('orc') && in_array(Request::input('orc'), explode(',', env('ORC_OPTIONS')))) {
                $country = Request::input('orc');
                if (Cookie::has('country')) {
                    Cookie::forget('country');
                }
            } elseif (Cookie::has('country')) {
                $country = Cookie::get('country');
            } else {
                $country = $user_real_country;
            }
    
            if (!is_null($country)) {
                Cookie::put('country', $country);
                $this->setLocale($country);
                $this->setuser_Locale($user_real_country);
            }
        }

    if (site_locale() == 'en-GB' && substr($uri, 0, 3) != '/gb') {
        Session::put('from_redirect', true);
        if(substr($uri, 0, 3) == '/ca') {
            return redirect(Config::getSiteUrl() . substr($uri, 4));
        }
        return redirect(Config::getSiteUrl() . ltrim($uri, '/'));
    } elseif (site_locale() == 'en-CA' && substr($uri, 0, 3) != '/ca') {
        Session::put('from_redirect', true);
        if(substr($uri, 0, 3) == '/gb') {
            return redirect(Config::getSiteUrl() . substr($uri, 4));
        }
        return redirect(Config::getSiteUrl() . ltrim($uri, '/'));
    } elseif(site_locale() == 'en' && (substr($uri, 0, 3) == '/ca' || substr($uri, 0, 3) == '/gb')) {
        Session::put('from_redirect', true);
        return redirect(Config::getSiteUrl() . substr($uri, 4));
    }

    return $next($request);
}


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3l7uXBX
via IFTTT

Call to undefined method App\Models\Meevo::getCategories()

$categories = $this->categoryRepository->getCategories($request); // $categories = Category::where('salon_id',$request->salon->salon_id)->with('services')->get(); if (!$request->session()->has('user') && $request->salon->show_login_home) { return view($request->salon->view_path . '.login'); } else { return view($request->salon->view_path . '.home', compact('categories')); }



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3jU04kV
via IFTTT

Callback 404 not found in login with google with Socialite

I have this link on my modal popup

<li><a href="" target="_blank"><i class="fab fa-google-plus-g"></i></a></li>

and routes is

Route::get('google', 'SocialiteAuthController@googleRedirect')->name('auth/google');
Route::get('/auth/google-callback',  'SocialiteAuthController@loginWithGoogle');

enter image description here

Services.php

'google' => [
    'client_id' => 'XXXXXXXXXXXXXXXX.apps.googleusercontent.com',
    'client_secret' => 'XXXXXXXXXXXXX',
    'redirect' => 'http://localhost:8000/login/google/callback',
],

Controller:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use Socialite;
use Illuminate\Support\Facades\Auth;
use Exception;

class SocialiteAuthController extends Controller
{
    public function googleRedirect()
    {
        return Socialite::driver('google')->redirect();
    }

     /**
     * Facebook login authentication
     *
     * @return void
     */
    public function loginWithGoogle()
    {
        try {
            $googleUser = Socialite::driver('google')->user();
            $user = User::where('google_id', $googleUser->id)->first();

            if($user){
                Auth::login($user);
                return redirect('/home');
            }

            else{
                $createUser = User::create([
                    'name' => $googleUser->name,
                    'email' => $googleUser->email,
                    'fb_id' => $googleUser->id,
                    'password' => encrypt('test@123')
                ]);

                Auth::login($createUser);
                return redirect('/home');
            }

        } catch (Exception $exception) {
            dd($exception->getMessage());
        }
    }
}

Guard :

 'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'user' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

but when i login i'm getting this page 404 not found

enter image description here

Any solution, Thanks



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3nh0XGA
via IFTTT

get value from an input using javascript and laravel

i need to get the value of the input with javascript.

Input:

<input id="user_id" value="5" name="user_id" type="hidden">

Controller:

 public function savetoken(Request $request)
{


    
    $this->validate($request, [
        'user_id'     =>  'required',
        'token'  =>  'required',
       ]);

        Notificaciones::create([
          'user_id'  => $request->user_id,
          'token' => $request->token
        ]);
  
        return back()->with('success', 'token saved successfully!');
}

How to get the Value of the Input that is Hidden? Javascript:

 function guardarToken(token){
    var formData=new FormData();
    formData.append('token',token);
    formData.append('user_id', user_id);

    var config = {
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"').content

        } 
    }

    axios.post('/token',formData, config).then( respuesta=>{
        console.log(respuesta);
    }).catch( e=>{
        console.log(e);
    });
}

I tried this way but I have not succeeded

help please



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3yWVQ0f
via IFTTT

mercredi 8 septembre 2021

What is the proper syntax to exclude rows that have a specific ID, but lack a row in a related table with a value in a column on that row?

Currently working on getting my head around the ordering of things, not even with laravel at first, but sql. Though the end goal is to use eloquent.

There are 2 conditions for the rows that need to be excluded. If I'm fetching the rows from TableA..

1) TableA with the column status_id (or TableC.id) has to have lets say a value of 1.

2) TableB has to have an instance for that TableA.id where status_id (or TableC.id) is lets say 2.

Been looking at whereNotIn, whereExists and when for a while now, but can't wrap my head around what is correct for the situation and how it should look like.

Still learning about sql queries and I am very grateful for any tips on this dilemma.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2X5qzLG
via IFTTT