jeudi 30 décembre 2021

Laravel 5.8 scheduler is not running commands

This question is asked before but non of the answers work for me. This is the Kernel.php

<?php

namespace App\Console;

use App\Console\Commands\TestRunKernel;
use App\Log;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;


class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        TestRunKernel::class
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        Log::create([
            'body' => 'test for log'
        ]);
        $schedule->call(function () {
           Log::create([
               'body' => 'test2 for log'
           ]);
        })->everyMinute();
        $schedule->command('test:run')->everyMinute();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__ . '/Commands');

        require base_path('routes/console.php');
    }
}

and this is the command

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Modules\User\Entities\User;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $user = User::find(1);
        $user->update([
            'file' => 1
        ]);
    }
}

The Kernel.php is running by cron job and test for log message is written in Log model. Hence I am sure the file is running by server. But when I use $schedule it doesn't work and non of the commands work. How can I fix this?

Thanks in advance.



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

mercredi 29 décembre 2021

Laravel 5.4: SQLSTATE[HY000]: General error: 1005 Can't create table "Foreign key constraint is incorrectly formed"

I'm using Laravel 5.4 and I have added this Migration:

public function up()
    {
        Schema::create('episodes', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('course_id')->unsigned();
            $table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
            $table->string('type', 10);
            $table->string('title');
            $table->string('slug');
            $table->text('description');
            $table->text('body');
            $table->string('videoUrl');
            $table->string('tags');
            $table->string('time', 15)->default('00:00:00');
            $table->integer('number');
            $table->integer('viewCount')->default(0);
            $table->integer('commentCount')->default(0);
            $table->integer('downloadCount')->default(0);
            $table->timestamps();
        });
    }

Now when I run php artisan migrate, I get this error:

SQLSTATE[HY000]: General error: 1005 Can't create table elearning.episodes (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table episodes add constraint episodes_course_id_foreign foreign key (course_id) references courses (id) on delete cascade)

I also tried this but still gets the same error:

$table->unsignedBigInteger('course_id');

So how can I properly run this Migration? I'm really stuck with this, please help me out...



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

include script in header for get params laravel

I´m traying to include in my blade other blade that contain script js to get any configuration parameters. But when load my page return this:

Uncaught SyntaxError: Invalid hexadecimal escape sequence

and

Uncaught ReferenceError: phpToJs is not defined

i´m inclining into my blade like this:


        @include('layouts.php_to_js')

and my blade contain this:

<script type="text/javascript">
    // global app configuration object
    var phpToJs = {
        url: {
            app_path: '{!! app_path() !!}',
            base_path: '{!! base_path() !!}',
            config_path: '{!! config_path() !!}',
            database_path: '{!! database_path() !!}',
            public_path: '{!! public_path() !!}',
            resource_path: '{!! resource_path() !!}',
            storage_path: '{!! storage_path() !!}',
            base_url: '{!! config("app.url") !!}',
            base_url_admin: '{!! config("app.url") !!}admin/',
            currentName: '{!! Route::currentRouteName() !!}',
            currentFull: '{!! Request::fullUrl() !!}',
            currentUrl: '{!! URL::current() !!}',
        },
        csrf: '{!! csrf_token() !!}',
        language: '{!! session()->get("language") !!}',
    };

</script>

i´m using this for to can use name routes in external files js (external to blade).If i show code for my website, it´s result:

<script type="text/javascript">
    // global app configuration object
    var phpToJs = {
        url: {
            app_path: 'C:\xampp\htdocs\gdsRepository\app',
            base_path: 'C:\xampp\htdocs\gdsRepository',
            config_path: 'C:\xampp\htdocs\gdsRepository\config',
            database_path: 'C:\xampp\htdocs\gdsRepository\database',
            public_path: 'C:\xampp\htdocs\gdsRepository\public',
            resource_path: 'C:\xampp\htdocs\gdsRepository\resources',
            storage_path: 'C:\xampp\htdocs\gdsRepository\storage',
            base_url: 'http://localhost/gdsRepository/public/',
            base_url_admin: 'http://localhost/gdsRepository/public/admin/',
            currentName: 'admin.precontratos.create',
            currentFull: 'https://localhost/gdsRepository/public/index.php/admin/precontratos/create',
            currentUrl: 'https://localhost/gdsRepository/public/index.php/admin/precontratos/create',
        },
        csrf: 'eoEE6xbNUQu53ze90x7dr1pCSE5lrEGugXsQldia',
        language: '',
    };

</script>    </head>

my script it´s there, but i can´t use it... any idea to solve my problems?

Thanks for read and help me. Sorry for my english



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

Laravel Date Mutators Nested Object

Person Collection

    {
      name: 'Jack',
      dateOfBirth: ISODate("1975-12-29T00:00:00.000Z")
      club: {
         name: 'A Club',
         joinedAt: ISODate("2020-10-29T14:12:01.309Z")
      }
    }

Person Model

protected $dates = ['dateOfBirth'];

How can I add the date fields in nested objects to this array?



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

mardi 28 décembre 2021

Laravel 5.4: Installation failed, reverting ./composer.json and ./composer.lock to their original content while trying to install a package [duplicate]

I'm working with Laravel 5.4 and I wanted to install Laravel Sluggable package but I got this error on the Terminal:

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - cviebrock/eloquent-sluggable[8.0.0, ..., 8.0.8] require illuminate/config ^8.0 -> found illuminate/config[v8.0.0, ..., v8.77.1] but these were not loaded, li
kely because it conflicts with another require.
    - Root composer.json requires cviebrock/eloquent-sluggable ^8.0 -> satisfiable by cviebrock/eloquent-sluggable[8.0.0, ..., 8.0.8].

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

And here is my Composer.json file:

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.6.4",
        "laravel/framework": "5.4.*",
        "laravel/tinker": "~1.0"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~5.7"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "scripts": {
        "post-root-package-install": [
            "php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ],
        "post-install-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postInstall",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postUpdate",
            "php artisan optimize"
        ]
    },
    "config": {
        "preferred-install": "dist",
        "sort-packages": true,
        "optimize-autoloader": true
    }
}

I don't know really what's going wrong here and how can I fix this issue.. So if you know please let me know, cause I really need it.



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

lundi 27 décembre 2021

why is the user being able to submit the POST even if the captcha is not verified?

I'm trying to set the google recaptcha, but whenever the user submits the form it gets verified, even if the captcha is not verified. Why can that be due to? I think everything is set up correctly with required and everything:

This is my registraton controller: I think the frontend is fine, as I can see and the captcha is interactive

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

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

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        $rules = [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'phone' => ['required', 'string', 'regex:/^([0-9\s\-\+\(\)]*)$/', 'min:8'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
            'g-recaptcha-response' => ['required', function ($attribute, $value, $fail) {
                $secretKey = "6LfGStAdAAAAAOQZWvjtATtnjmGc48YoMTtfrxPc";
                $response = $value;
                $userIP = $_SERVER['REMOTE_ADDR'];
                 $url = 'https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$response&remoteip=$userIP';
                 $response = \file_get_contents($url);
                 $response = json_decode($response);
                 if (!$response->success) {
                     Session::flash("g-recaptcha-response", "Please check the the captcha form.");
                     Session::flash("alert-class", "alert-danger");
                     $fail('The recaptcha is not valid');
                 } 
             }
            ],
        ];
        if (config('settings.enable_birth_date_on_register') && config('settings.minimum_years_to_register')) {
            $rules['birth_date'] = 'required|date|date_format:Y-m-d|before:-'.config('settings.minimum_years_to_register').' years';
        }
        //dd($rules);
        return Validator::make($data, $rules);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        /*return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'phone' => $data['phone'],
            'password' => Hash::make($data['password']),
            'api_token' => Str::random(80)
        ]);*/

        //dd($data);

        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'phone' => $data['phone'],
            'password' => Hash::make($data['password']),
            'api_token' => Str::random(80),
            'birth_date' => isset($data['birth_date']) ? $data['birth_date'] : ''
        ]);

        $user->assignRole('client');

        //Send welcome email
        //$user->notify(new WelcomeNotification($user));

        return $user;
    }

    protected function registered(Request $request, User $user)
    {
        if (config('settings.enable_sms_verification')) {
            // $user->callToVerify();
        }

        return redirect($this->redirectPath());
    }
}


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

dimanche 26 décembre 2021

Laravel 5.8 , customize register controller but weirdly not working, how to solve this error?

Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, string given, called in /home/mumildup/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Auth/RegistersUsers.php on line 35 {"userId":1,"exception":"[object] (Symfony\Component\Debug\Exception\FatalThrowableError(code: 0): Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, string given, called in /home/mumildup/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Auth/RegistersUsers.php on line 35 at /home/mumildup/laravel/vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php:405)



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

LaraCSV export error ( Because of big data)

I have this code in my laravel project which creates and downloads CSV from Laravel Query $csvExporter->build($example_users, $example_headers, array('header'=>true))->download($fileName); But i am getting internal error because the $example_users table is too big. I know that there is some way to do it with chunks e.c (LaraCSV Repo) But can't configure out how. Please help



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

How to use old Laravel routing style in Laravel 8

I just installed Laravel 8 and in this version, I have to type my routes like this:

Route::get('/admin/panel', [App\Http\Controllers\Admin\PanelController::class, 'index']);

But I got used to Laravel 5 routes which looked like this:

Route::namespace('Admin')->prefix('admin')->group(function () {
    Route::get('/panel', 'Admin/PanelController@index');
});

So how can I use this Laravel 5 routing inside Laravel 8 version?



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

samedi 25 décembre 2021

Eloquent relationship give [ticket_id] does not exist on this collection instance laravel

I am have some issue with eloquent relationship my first time working with it, after selecting and displaying list of selected events, I want to also select the ticket_id base on the event_id common between both(events and events_ticket) table, thanks for the help

Error Showing -> Trying to get property 'ticket_id' of non-object (View: C:\wamp64\www\mahive\resources\views\tickets\index.blade.php)

Both Model

class EventsTicket extends Model
{
    public $table = "events_ticket";
    use HasFactory;
    protected $fillable = [
        'event_id',
        'ticket_id',
        'ticket_name',
        'ticket_amount',
        'ticket_sold',
    ];

    public function event() {
        return $this->belongsTo('App\Models\Event');
    }
}

class Event extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'event_id',
        'event_name',
        'event_category',
        'event_type',
        'event_mode',
        'event_description',
        'event_image'
    ];

    public function userModel() {
        return $this->belongsTo('App\Models\User');
    }

    public function eticket() {
        return $this->hasMany('App\Models\EventsTicket');
    }
}

Controller

public function index()
{
    $events = Event::where('ticket_statue', 'active')->with('eticket')->get();
    return view('tickets.index', ['event_data' => $events]); 
}

View

@foreach($event_data as $event)
    
    
@endforeach


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

MongoDB Class 'MongoDB\Driver\Manager' not found" in Laravel 5.7, php 7.3 (on Ubuntu 20.4 and Apache)

I am running a laravel 5.7 app on apache server which i have tried on the different php versions(7.2, 7.3) i have installed on my ubuntu system. Upon hitting the apps url in the browser i get this error Class 'MongoDB\Driver\Manager' not found I have been battling with this for a while now and have tried so many solutions out there but it still persists. I have mongodb extension installed on all the php distributions. Funny enough, When i tried getting a record from the db using tinker it works very fine.



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

vendredi 24 décembre 2021

Handling token expired in Laravel JWT

I'm using tymondesigns/jwt-auth in Laravel and angular application, this is the code i'm using i'm getting token expired error from laravel end in my network tab when idle time is more than 20-30 min but my ttl value is 1440, and front end user should get message in popup that their session expire rather than getting 500 error in console.

jwt.php

<?php

/*
 * This file is part of jwt-auth.
 *
 * (c) Sean Tymon <tymon148@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

return [

    /*
    |--------------------------------------------------------------------------
    | JWT Authentication Secret
    |--------------------------------------------------------------------------
    |
    | Don't forget to set this in your .env file, as it will be used to sign
    | your tokens. A helper command is provided for this:
    | `php artisan jwt:secret`
    |
    | Note: This will be used for Symmetric algorithms only (HMAC),
    | since RSA and ECDSA use a private/public key combo (See below).
    |
    */

    'secret' => env('JWT_SECRET'),

    /*
    |--------------------------------------------------------------------------
    | JWT Authentication Keys
    |--------------------------------------------------------------------------
    |
    | The algorithm you are using, will determine whether your tokens are
    | signed with a random string (defined in `JWT_SECRET`) or using the
    | following public & private keys.
    |
    | Symmetric Algorithms:
    | HS256, HS384 & HS512 will use `JWT_SECRET`.
    |
    | Asymmetric Algorithms:
    | RS256, RS384 & RS512 / ES256, ES384 & ES512 will use the keys below.
    |
    */

    'keys' => [

        /*
        |--------------------------------------------------------------------------
        | Public Key
        |--------------------------------------------------------------------------
        |
        | A path or resource to your public key.
        |
        | E.g. 'file://path/to/public/key'
        |
        */

        'public' => env('JWT_PUBLIC_KEY'),

        /*
        |--------------------------------------------------------------------------
        | Private Key
        |--------------------------------------------------------------------------
        |
        | A path or resource to your private key.
        |
        | E.g. 'file://path/to/private/key'
        |
        */

        'private' => env('JWT_PRIVATE_KEY'),

        /*
        |--------------------------------------------------------------------------
        | Passphrase
        |--------------------------------------------------------------------------
        |
        | The passphrase for your private key. Can be null if none set.
        |
        */

        'passphrase' => env('JWT_PASSPHRASE'),

    ],

    /*
    |--------------------------------------------------------------------------
    | JWT time to live
    |--------------------------------------------------------------------------
    |
    | Specify the length of time (in minutes) that the token will be valid for.
    | Defaults to 1 hour.
    |
    | You can also set this to null, to yield a never expiring token.
    | Some people may want this behaviour for e.g. a mobile app.
    | This is not particularly recommended, so make sure you have appropriate
    | systems in place to revoke the token if necessary.
    | Notice: If you set this to null you should remove 'exp' element from 'required_claims' list.
    |
    */

    'ttl' => env('JWT_TTL',1440),

    /*
    |--------------------------------------------------------------------------
    | Refresh time to live
    |--------------------------------------------------------------------------
    |
    | Specify the length of time (in minutes) that the token can be refreshed
    | within. I.E. The user can refresh their token within a 2 week window of
    | the original token being created until they must re-authenticate.
    | Defaults to 2 weeks.
    |
    | You can also set this to null, to yield an infinite refresh time.
    | Some may want this instead of never expiring tokens for e.g. a mobile app.
    | This is not particularly recommended, so make sure you have appropriate
    | systems in place to revoke the token if necessary.
    |
    */

    'refresh_ttl' => env('JWT_REFRESH_TTL', 20160),

    /*
    |--------------------------------------------------------------------------
    | JWT hashing algorithm
    |--------------------------------------------------------------------------
    |
    | Specify the hashing algorithm that will be used to sign the token.
    |
    | See here: https://github.com/namshi/jose/tree/master/src/Namshi/JOSE/Signer/OpenSSL
    | for possible values.
    |
    */

    'algo' => env('JWT_ALGO', 'HS256'),

    /*
    |--------------------------------------------------------------------------
    | Required Claims
    |--------------------------------------------------------------------------
    |
    | Specify the required claims that must exist in any token.
    | A TokenInvalidException will be thrown if any of these claims are not
    | present in the payload.
    |
    */

    'required_claims' => [
        'iss',
        'iat',
        'exp',
        'nbf',
        'sub',
        'jti',
    ],

    /*
    |--------------------------------------------------------------------------
    | Persistent Claims
    |--------------------------------------------------------------------------
    |
    | Specify the claim keys to be persisted when refreshing a token.
    | `sub` and `iat` will automatically be persisted, in
    | addition to the these claims.
    |
    | Note: If a claim does not exist then it will be ignored.
    |
    */

    'persistent_claims' => [
        // 'foo',
        // 'bar',
    ],

    /*
    |--------------------------------------------------------------------------
    | Lock Subject
    |--------------------------------------------------------------------------
    |
    | This will determine whether a `prv` claim is automatically added to
    | the token. The purpose of this is to ensure that if you have multiple
    | authentication models e.g. `App\User` & `App\OtherPerson`, then we
    | should prevent one authentication request from impersonating another,
    | if 2 tokens happen to have the same id across the 2 different models.
    |
    | Under specific circumstances, you may want to disable this behaviour
    | e.g. if you only have one authentication model, then you would save
    | a little on token size.
    |
    */

    'lock_subject' => true,

    /*
    |--------------------------------------------------------------------------
    | Leeway
    |--------------------------------------------------------------------------
    |
    | This property gives the jwt timestamp claims some "leeway".
    | Meaning that if you have any unavoidable slight clock skew on
    | any of your servers then this will afford you some level of cushioning.
    |
    | This applies to the claims `iat`, `nbf` and `exp`.
    |
    | Specify in seconds - only if you know you need it.
    |
    */

    'leeway' => env('JWT_LEEWAY', 0),

    /*
    |--------------------------------------------------------------------------
    | Blacklist Enabled
    |--------------------------------------------------------------------------
    |
    | In order to invalidate tokens, you must have the blacklist enabled.
    | If you do not want or need this functionality, then set this to false.
    |
    */

    'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true),

    /*
    | -------------------------------------------------------------------------
    | Blacklist Grace Period
    | -------------------------------------------------------------------------
    |
    | When multiple concurrent requests are made with the same JWT,
    | it is possible that some of them fail, due to token regeneration
    | on every request.
    |
    | Set grace period in seconds to prevent parallel request failure.
    |
    */

    'blacklist_grace_period' => env('JWT_BLACKLIST_GRACE_PERIOD', 0),

    /*
    |--------------------------------------------------------------------------
    | Cookies encryption
    |--------------------------------------------------------------------------
    |
    | By default Laravel encrypt cookies for security reason.
    | If you decide to not decrypt cookies, you will have to configure Laravel
    | to not encrypt your cookie token by adding its name into the $except
    | array available in the middleware "EncryptCookies" provided by Laravel.
    | see https://laravel.com/docs/master/responses#cookies-and-encryption
    | for details.
    |
    | Set it to true if you want to decrypt cookies.
    |
    */

    'decrypt_cookies' => false,

    /*
    |--------------------------------------------------------------------------
    | Providers
    |--------------------------------------------------------------------------
    |
    | Specify the various providers used throughout the package.
    |
    */

    'providers' => [

        /*
        |--------------------------------------------------------------------------
        | JWT Provider
        |--------------------------------------------------------------------------
        |
        | Specify the provider that is used to create and decode the tokens.
        |
        */

        'jwt' => Tymon\JWTAuth\Providers\JWT\Lcobucci::class,

        /*
        |--------------------------------------------------------------------------
        | Authentication Provider
        |--------------------------------------------------------------------------
        |
        | Specify the provider that is used to authenticate users.
        |
        */

        'auth' => Tymon\JWTAuth\Providers\Auth\Illuminate::class,

        /*
        |--------------------------------------------------------------------------
        | Storage Provider
        |--------------------------------------------------------------------------
        |
        | Specify the provider that is used to store tokens in the blacklist.
        |
        */

        'storage' => Tymon\JWTAuth\Providers\Storage\Illuminate::class,

    ],

];

Auth Controller.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Auth\Events\Verified;
use Validator;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Notification;

class AuthController extends Controller
{
   
    public function __construct() {
        $this->middleware('auth:api', ['except' => ['login', 'register']]);
    }

     /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request){
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|string|min:6',
        ]);

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

        if (! $token = auth()->attempt($validator->validated())) {
            return response()->json(['status'=>true,'error_message' => 'Invalid Credentials'], 401);
        }

        return $this->createNewToken($token);
    }

      /**
     * Register a User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request) {
        $messages = [
            'password.confirmed' => 'Password Confirmation should match the Password',
            'password.min' => ' Password should be minimum 6 digits',
        ];
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|between:2,100',
            'email' => 'required|string|email|max:100|unique:users',
            'password' => 'required|string|confirmed|min:6',
        ],$messages);

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

        $user = User::create(array_merge(
                    $validator->validated(),
                    ['password' => bcrypt($request->password)]
                ));

        return response()->json([
            'message' => 'Successfully registered',
        ], 201);
    }

      /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout() {
        auth()->logout();

        return response()->json(['message' => 'User successfully signed out']);
    }

      /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh() {
        return $this->createNewToken(auth()->refresh());
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function userProfile() {
        return response()->json(auth()->user());
    }

     /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function createNewToken($token){
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60,
            'user' => auth()->user()
        ]);
    }
}

api.php

Route::group([
    'middleware' => ['api'],
    'prefix' => 'auth'

], function ($router) {
    Route::post('/login', [AuthController::class, 'login'])->name('login');
    Route::post('/register', [AuthController::class, 'register']);
    Route::post('/logout', [AuthController::class, 'logout']);
    ..
});

Angular Code:

Auth Interceptor.ts

import { Injectable } from "@angular/core";
import { HttpInterceptor, HttpRequest, HttpHandler } from "@angular/common/http";
import { TokenService } from "../shared/token.service";

@Injectable()

export class AuthInterceptor implements HttpInterceptor {
    constructor(private tokenService: TokenService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler) {
        const accessToken = this.tokenService.getToken();
        req = req.clone({
            setHeaders: {
                Authorization: "Bearer " + accessToken
            }
        });
        return next.handle(req);
    }
}

token_service.ts

import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})

export class TokenService {
  baseUrl = environment.baseUrl;

  private issuer = {
    login: this.baseUrl+'api/auth/login',
    register: this.baseUrl+'api/auth/register'
  } 

  constructor() { }

  handleData(token  : any){
    localStorage.setItem('auth_token', token);
  }

  getToken(){
    return localStorage.getItem('auth_token');
  }

  // Verify the token
  isValidToken(){
     const token = this.getToken();

     if(token){
       const payload = this.payload(token);
       if(payload){
         return Object.values(this.issuer).indexOf(payload.iss) > -1 ? true : false;
       }
     } else {
        return false;
     }
  }

  payload(token  : any) {
    const jwtPayload = token.split('.')[1];
    return JSON.parse(atob(jwtPayload));
  }

  // User state based on valid token
  isLoggedIn() {
    return this.isValidToken();
  }

  // Remove token
  removeToken(){
    localStorage.removeItem('auth_token');
  }

}

Error: enter image description hereAny Solution Thanks



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

jeudi 23 décembre 2021

problem with session in iOS Safari - laravel

I have a problem with iOS devices, i working with laravel and sessions,

i using a payment module, the answer that the process gives me but is Null

in other browsers with Android system it does not lose the session

public function invoke(Request $request) {
    
      $payment_id = $request->get('payment_id');
    
    
      $response = Http::get("https://api.mercadopago.com/v1/payments/$payment_id" . "?access_token=TEST-CODEX-349463544506SADSA7");
      
      $response = json_decode($response);
    
      $request->session()->put('order', $response->order->id);
      $request->session()->put('ingreso', $response->transaction_details->net_received_amount);
      $request->session()->put('monto', $response->transaction_details->total_paid_amount);
      $request->session()->put('metodo', $response->payment_type_id); 
     $status = $response->status;
    
    
     if($status == 'approved') {
    
    
      Ingresosmp::insert([
        'user_id'       => Session::get('user_id'),
        'evento_id'       => Session::get('variableName'),
        'mp_id'  => Session::get('order'),
        'metodo'        => Session::get('metodo'),
        'monto'        => Session::get('monto'),
        'ingreso'        => Session::get('ingreso'),
    
    
      ]);
    
     
      
    
      return redirect('success')->with('success', 'okAY!');
    
    
    }

Image with problem:

https://i.imgur.com/nNUrhSL.png

help pls



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

json_encode() returns false - Laravel Model Class

When i am trying to encode model class its not working. Its showing error named "Malformed UTF-8 characters"

$json_array = json_encode(Product::all()); // returns false
// json_last_error_msg() shows error message titled "Malformed UTF-8 characters, possibly incorrectly encoded"

Product title contains "Bengali Language". Sample given below

  [▼
  "id" => 4996
  "product_type" => "Goods"
  "name" => "আমাল"
  ]

How can i solve this error??



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

"A token is required" in JWT Laravel

I was trying to get the details of logged in user got this link

 use JWTAuth;
 $user=JWTAuth::toUser($token);

i tried this also $user = auth()->user(); getting NULL

$token variable is same which i have i browser local storage.

this link i found but this is not working in my case.

Tymon\JWTAuth::toUser error: A token is required



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

Cannot Access user profile using JWT in Laravel

I have used JWT in Laravel for user Authentication

Auth Controller:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Auth\Events\Verified;
use Validator;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Notification;

class AuthController extends Controller
{
   
    public function __construct() {
        $this->middleware('auth:api', ['except' => ['login', 'register']]);
    }

     /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request){
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|string|min:6',
        ]);

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

        if (! $token = auth()->attempt($validator->validated())) {
            return response()->json(['status'=>true,'error_message' => 'Invalid Credentials'], 401);
        }

        return $this->createNewToken($token);
    }

      /**
     * Register a User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request) {
        $messages = [
            'password.confirmed' => 'Password Confirmation should match the Password',
            'password.min' => ' Password should be minimum 6 digits',
        ];
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|between:2,100',
            'email' => 'required|string|email|max:100|unique:users',
            'password' => 'required|string|confirmed|min:6',
        ],$messages);

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

        $user = User::create(array_merge(
                    $validator->validated(),
                    ['password' => bcrypt($request->password)]
                ));

        return response()->json([
            'message' => 'Successfully registered',
        ], 201);
    }

      /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout() {
        auth()->logout();

        return response()->json(['message' => 'User successfully signed out']);
    }

      /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh() {
        return $this->createNewToken(auth()->refresh());
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function userProfile() {
        return response()->json(auth()->user());
    }

     /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function createNewToken($token){
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60,
            'user' => auth()->user()
        ]);
    }



}

routes :

Route::group([
    'middleware' => ['api'],
    'prefix' => 'auth'

], function ($router) {
    Route::post('/login', [AuthController::class, 'login']);
    Route::post('/register', [AuthController::class, 'register']);
    Route::post('/logout', [AuthController::class, 'logout']);
    Route::post('/refresh', [AuthController::class, 'refresh']);
    Route::get('/user-profile', [AuthController::class, 'userProfile']); 

Login and register is working

but when i access user-profile route getting this error :

Symfony\Component\Routing\Exception\RouteNotFoundException: Route [login] not defined. in file C:\wamp64\www\project\vendor\laravel\framework\src\Illuminate\Routing\UrlGenerator.php on line 420

and i cannot get id of user if some user is logged in using : auth()->user()->id

auth.php

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

        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
            'hash' => false,
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    ],

Model :

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
#use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{   #HasFactory, 
     use Notifiable;

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

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function getJWTIdentifier() {
        return $this->getKey();
    }

    public function getJWTCustomClaims() {
        return [];
    }    

}

Any suggestion is highly appreciated

Thanks



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

Insert array data in separate database row in a field not the same Laravel

I am trying to insert an array data into the database, on form submit with the following input field (Name, Age, Amount) but I am getting Array to string conversion Error, so I added json_encode() to the variable to prevent the error, but the issue now is on insertion into the database, the array data is inserting the data in the same row, I want it in different row of same filed, see below image thanks

enter image description here

B is the result I want to get

Controller

    public function store(Request $request)
    {

    $userid = rand(10000,99999);
    $username = $request->get('uname');
    $userage = json_encode($request->get('uage'));
    $useramount = json_encode($request->get('uamount');


    if (isset($username)){
        foreach ( $request->get('uname') as $username) {
            $add[] = [
                'user_id' => $userid,
                'user_name' => $username,
                'user_age' => $userage,
                'user_amount' => $useramount,
            ];
        }
        Person::insert($add);
    }

}


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

mercredi 22 décembre 2021

How to automatically reorder/sort div according to highest id

I want to automatically reorder/sort a div according to the highest vote count once an ajax call is done, I have tried many thing codes and none seems to be working. Below is the code.

@foreach($candidates->sortByDesc("voteCount") as $candidate) 
                <div class="col-md-6" id="">// this is the div I want to reorder
        <div class="card">
        <div class="card-header">
                    <h4 class="card-title" id="heading-multiple-thumbnails"> </h4>
                    <a class="heading-elements-toggle">
                        <i class="la la-ellipsis-v font-medium-3"></i>
                    </a>
                    
                </div>
        </div>
    </div>
            @endforeach

The Javascript

  
         $('.castVoteForCandidateButton').on('click', function (e) {
             $("#voteCofirmStatus").hide();
             $("#voteProccessStatus").show();
             $.ajax({
                    type:'POST',
                    url:'/vote',
                    data:{candidateId : candidateId, _token: "<?php echo csrf_token(); ?>",name:name ,position:position},
                    success:function(data){
                         if(data.status =='ok' ){
                             setTimeout(function() {$('#voteProcessingModal').modal('hide');}, 500);
                            $("#voteProccessStatus").hide();
                            $("#voteSuccessStatus").show().text('Nice job!,you have successfully voted for '+ data.name);
                            $("#voteCount"+data.id).text(parseFloat(data.voteCount)+" Votes");
                            $("#confirmCandidateVoteButton"+data.id).hide();
                            var div = $("#voteCount"+data.id);
                            div.animate({fontSize: "30px"}, "slow");
                            div.animate({fontSize: "17px"}, "slow");


         const main = document.querySelector('#main');// this
        const divs = [...main.children];// is
        divs.sort((a, b) => a.id - b.id);// the 
        divs.forEach(div => main.appendChild(div));// Latest code I tried and its not working
                             }else{
                                 $("#voteErrorStatus").show().text(data);
                                 
                             }
                       }
                     });  
         } );


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

Can I use a Models scope with Laravel's 5.5 Query Builder Join method?

I am trying to use Laravel 5.5 Query Builders Join method with a scope method from the CommercialCoupon Model but when I try to apply this scope I get this error:

[2021-12-22 23:18:16] lumen.ERROR: BadMethodCallException: Call to undefined method Illuminate\Database\Query\JoinClause::filterBlockedCoupons() in /var/www/new-api/vendor/illuminate/database/Query/Builder.php:2483

My CommercialCoupon Model has this scope:

public function scopeFilterBlockedCoupons($query, $channelPartnerId){
    $query->whereNotIn('discount_provider_id', function($subquery) use ($channelPartnerId)
        {
            $subquery->select('discount_providers.id')
            ->from('discount_providers')
            ->join('discount_provider_permissions', function($join)
            {
                $join->on('discount_provider_permissions.discount_provider_id', '=', 'discount_providers.id' );
                $join->on('discount_providers.block_type', '=', \DB::raw(Config::get('systemtype.discount_provider_block_types.deny')));
            })
            ->where('discount_provider_permissions.channel_partner_id', '=', \DB::raw($channelPartnerId));
        })
    ->whereNotIn('discount_provider_id',  function($subquery) use ($channelPartnerId)
        {
            $subquery->select(\DB::raw('
                CASE WHEN COUNT(discount_provider_permissions.id) > 0 then
                    -1
                ELSE
                    discount_providers.id
                END
                AS excludedDiscountProviderId'))
            ->from('discount_providers')
            ->leftJoin('discount_provider_permissions', function($join) use ($channelPartnerId)
            {
                $join->on('discount_provider_permissions.discount_provider_id', '=', 'discount_providers.id' );
                $join->on('discount_provider_permissions.channel_partner_id', '=', \DB::raw($channelPartnerId) );
            })
        ->where('discount_providers.block_type', '=', \DB::raw(Config::get('systemtype.discount_provider_block_types.allow')))
        ->groupBy('discount_providers.id');
    });
}

This scope works perfectly if I'm calling the CommercialCoupon Model directly.

When I try to use this scope inside of a join displayed in the code below I get the error above:

$coupons = Carousel::where('carousels.channel_partner_id', '=', $selectedChannelPartnerId)
    ->join('carousel_contents', 'carousels.id', '=', 'carousel_contents.carousel_id')
    ->join('commercial_coupons', function ($join) use ($channelPartnerId) {
        $join->on('commercial_coupons.id', '=', 'carousel_contents.table_id')
            ->filterBlockedCoupons($channelPartnerId);
    })
    ->join('discount_providers', 'discount_providers.id', '=', 'commercial_coupons.discount_provider_id')
    ->where('carousel_contents.table_name', '=', \DB::raw("'commercial_coupons'"))
    ->select("commercial_coupons.logo_image AS marketing_image", "commercial_coupons.id AS coupon_id", "discount_providers.name as discount_provider_name", "commercial_coupons.coupon_org_name as coupon_title", "commercial_coupons.discount_provider_id")
    ->orderBy('carousel_contents.order')
    ->get();

Am I able to use the scope on the Model or do I just have to copy and paste the code inside the scope this specific join?



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

mardi 21 décembre 2021

upload and minimize several images with livewire in a sails container

I am working on a laravel project with docker containers. The project therefore uses a sails container. I have an input in a form for uploading photos with livewire. But I have a problem as soon as the total of uploaded images exceeds 100MB. I have 2 questions: the blocking beyond 100MB depends on sails or livewire and how to configure it?

with livewire, if I want to use a third party API like tinyPNG to minimize images can I do this between when livewire creates temporary files and when it permanently stores the files? or when it creates the temporary files, I am already limited by the global maximum size of the upload?

thanks.



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

laravel dynamic drop down not giving value

im using ajax for laravel dropdown it was working but when i tiring to submit form it was giving id number

im getting right input in dropdown field when i try to submit page it was giving id number instead of dropdown value i what to get value of MS OFFICE AND 1000 BUT IT STORING IN DATA BASCE {COURES TYPE C_1402:} { COURSE PRICE C_1402:}

my view enter image description here

my network tab showing this id enter image description here my view page

 <div class="col-md-4">
                                        <div class="form-group">
                                            <label for="location1">Course Type  :<span class="danger">*</span> </label>
                                            <select class="custom-select form-control required" name="student_course" id="student_courses" name="location" required>
                                            <option value="">Select Course</option>
                                                @foreach ($course_name as $key => $value)
                                                    <option value=""></option>
                                                @endforeach
                                          
                                            </select>  
                                        </div>
                                    </div>

  <div class="col-md-3">
                                            <div class="form-group">
                                                <label for="videoUrl1">Course Price :</label>
                                                <select name="course_Price" id="course_Prices" class="form-control dynamic" data-dependent="course_Price">
                                                <option value=""></option>
                                                </select>
                                            </div>
                                        </div>

ajax

 <script type="text/javascript">
    $(document).ready(function() {
        $('#student_courses').on('change', function() {
            var stateID = $(this).val();
            if(stateID) {
                $.ajax({
                    url: '/Student_Course_get_price/'+stateID,
                    type: "GET",
                    dataType: "json",
                    success:function(data) {                      
                        $('#course_Prices').empty();
                        $.each(data, function(key, value) {
                        $('#course_Prices').append('<option value="'+ key +'">'+ value +'</option>');
                        });
                    }
                });
            }else{
                $('#course_Prices').empty();
            }
        });
    });
</script>

my controller

   public function Student_Course_get()
    {
        $course_name = DB::table("courses")->pluck('COURSE_NAME','COURSE_NAME_id');        
        return view('Admin/Student.Student_enrollment',compact('course_name'));
    }

    public function Student_Course_get_price($COURSE_NAME_id)
    {
        $cities = DB::table("courses")
                    ->where("C_id",$COURSE_NAME_id)
                    ->pluck('COURSE_AMOUNT','C_id');
        return json_encode($cities);
    }


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

lundi 20 décembre 2021

Custom Form Request Validation with unique validation not working on update

I'm not sure what I'm doing wrong, but I have a custm form request validation that I'm using in for Create and Update record with unique column validation. It working fine for create creating new record, but not in updating.

Custome Form Request

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ServiceTypeRequest extends FormRequest
{

public function authorize()
{
    return true;
}

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'service_name'        => ['required', Rule::unique('service_type', 'Service')->ignore($this->service_type) ],
        'type'                => ['required', 'string'],
        'view_availability'   => ['required', 'boolean'],

    ];
 }
}

Controller Update

public function update(ServiceTypeRequest $request, ServiceType $serviceType)
{
    $validated = $request->validated();

    $service_type = ServiceType::update([
        'Service'               => $validated['service_name'],
        'type'                  => $validated['type'],
        'view_availability'     => $validated['view_availability'],
    ]);

    return redirect()
            ->route('service_type.index')
            ->with('status', 'Service type updated!');
}

Error Getting when I submit the update form with PUT method It's complain about the $this I have inside the custom form validation for service_name.

Error
Using $this when not in object context
http://localhost:8021/service_type/58 


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

dimanche 19 décembre 2021

Limit the rate of emails sent with Laravel

I am creating a forum with Laravel and as soon as a new private message or a new message in a thread where the user has participated, an email is sent. However, I have a problem: if a user receives 60 private message within an hour then he will receive 60 private message to notify him that he has a new message.

Is it possible to limit the number of emails sent per hour for example ? Is there a attribute to change somewhere ?

Here is an example of the function to find the recipient + send the private message in the MessagesController:

public function newPrivateMessage(Thread $thread, $urlToAccess){
        /* We retrieve the ID of the person connected */
        $userId = Auth::id();//auth()->user()->id
        /* We get the other user from the discussion. */
        $user = $thread->participants->where('user_id', '<>', $userId)->first();
        $userName = User::find($user->user_id);
        /* For the recipient, send an email */
        Mail::to($userName->email)->send(new NewPrivateMessageMail($user,$urlToAccess));
    }

And I've created a NewPrivateMessage inside my http folder with this artisan command php artisan make:mail NewPrivateMessage.

public function __construct($user,$urlToAccess)
{
    $this->data = $user;
    $this->url = $urlToAccess;
}

public function build()
{
    return $this
       ->subject('New private message')
       ->markdown('emails.markdown-newPrivateMessage');
}
```

Cordially


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

samedi 18 décembre 2021

Fetch and display table data in angular and laravel

I'm trying to display data fetched from laravel api in angular table code is :

public function fetchQuestions(Request $request)
{  
  $questions = Questions::where('status',$request->status)->get();
  return response()->json($questions, 200);
}

angular code:

 questions = [];
  ...
  this.http.post(this.baseUrl+'api/auth/question', formData).subscribe(result  => {
  this.questions.push(result);

This does not display any data

i have to use

  this.questions.push(result[0]);
  this.questions.push(result[1]);
  ..
  ..
  this.questions.push(result[n]);

to push all the data. How can i push all array data.

and display data using loop

<ng-container *ngFor="let img of questions; let i=index">


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

vendredi 17 décembre 2021

Cannot store file in storage folder in Laravel

I'm trying to store file in storage folder

 if(!Storage::exists('/public/files')) {
          Storage::makeDirectory('/public/files', 0777, true); //creates directory
        }
 Storage::put('/public/files/test.wav', file_get_contents($blobInput));

but directory and files are not getting created, I have tried php artisan:storage:link

but same issue. Thanks



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

Email sending stop when I use my domain name in email contents in Laravel [closed]

My application was working fine, suddenly, a member verification email forgot password email, and other email stops to work.

I tried to find out the issue and I got the reason, in which email contents has my domain name, that was not working. So I have removed my domain name from some email contents and those have started to work.

But member verification email and forgot password email must need a domain URL for verification URL and update password URL.

This is very strange why the domain name/link not working in my email contents.

I am using Gmail mail sender:

MAIL_DRIVER=sendmail
MAIL_HOST=smtp.gmail.com
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

Please help me to solve this issue.

Thank you



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

success message issue in JQuery from Laravel controller

I have submitted the json response from laravel controller but when it gives error the JQuery section is working fine but when the request succeeds the JQuery gives error that parase error and I am not able to read the data content but it shows the data in log console correctly.

JQuery Ajax code : ----------------------------

event.preventDefault();
url = $('a#sendpropertiesdata').attr('href');
data = new FormData($('#propertiescreateform')[0]);



$.ajax({
    url: url,
    type: "POST",
    data: data,
    processData: false,
    dataType: 'json',
    contentType: false,
    beforeSend:function(){
    },
    success:function(data){
       // alert(data.msg);
        response = data
        alert(response['code']);
        if (data.code == 0 ){
            $('span#error_message').text(data.error).css('color','red');
        }else if (data.code == 1){
            $('span#error_message').text(data.msg).css('color','green');
            window.setTimeout(function(){
                $('form#propertiescreateform').remove();
                 }, 3000);
        }

    },
    complete: function(data, status ){
        alert(data.code + "     "  + status );
        if (data.code == 1  ){
            $('span#error_message').text(data.msg).css('color','green');
            window.setTimeout(function(){
                $('form#propertiescreateform').remove();
                 }, 3000);
                }
    }  
 });

Controller Code -----------------------------------------------------------

$validator = \Validator::make($request -> all(), $rules); 
               if ($validator -> passes()){
                    $property = new Properties();
                    $property -> country = $request -> country ; 
                    $property -> city = $request -> housecity ; 
                    $property -> location = $request -> houseaddress ;
                    $property -> description = $request -> propertiesdescription ;
     
                    $property -> price = $request -> price; 
                         $property -> save();   
                         
                         return response() -> json(['code' => 1, 'msg' => 'data saved successfully']);
                        } 
               }else {
                return response() -> json(['code' => 0, 'error' => $validator -> errors()->all()]);
               }


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

Access denied for user 'user'@'localhost' Laravel 5.8

I have this project running on Laravel 5.8 and Database on Mysql using XAMPP server.

This is my .env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

This is my config/database.php file:

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => false,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

and also created a Database in Xampp named homestead.

this error is showing: SQLSTATE[HY000] [1045] Access denied for user 'user'@'localhost' (using password: YES) (SQL: select * from userswhereemail = test@gmail.com



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

jeudi 16 décembre 2021

Laravel 5 - Form not appearing on page

So I created a form in a blade file, that looks like this: student.blade.php My Controller looks like this: StudentController.php And my route looks like this: web.php Here is the output I get, missing the form: enter image description here

I am wondering if I am missing something? Or what is going wrong here?



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

Property [image] does not exist on this collection instance. / Laravel - with() Method

I get data with relations from controller but can't use in blade

Controller..

$employees = Post::where('user_id', $user_id)->with('people')->get();

Blade, I use in foreach like ..

$employee->people->image

But it gives error

Property [image] does not exist on this collection instance.



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

Case statement sum time difference return zero with multiple conditions

I am working with laravel eloquent query with this case statement structure (sum time difference between start and end time, if records created within a current week in timelogs table and project is billable in projects table)result return always zero. please help I don't understand.

$billable_data = Project::where(['active' => 1, 'company_id' => session('company_id'), 'is_deleted' => 0])
        ->join('timelogs','timelogs.project_id','=','projects.id')
        ->select(DB::raw('CASE WHEN (billable = 1 AND timelogs.created_at BETWEEN "'.$monday.' 00:00:00" AND "'.$friday.' 23:59:59") THEN SUM(TIMESTAMPDIFF(second, timelogs.start_time, timelogs.end_time))  ELSE 0 END as billable_hours,
            CASE WHEN (billable = 0 AND timelogs.created_at BETWEEN "'.$monday.' 00:00:00" AND "'.$friday.' 23:59:59") THEN SUM(TIMESTAMPDIFF(second, timelogs.start_time, timelogs.end_time))  ELSE 0 END as non_billable_hours'))
        ->first()->toArray();

dd result of $billable_data :

array:3 [▼
"billable_hours" => "0"
"non_billable_hours" => "0"
]

But when I used this raw query within DB::raw everything worked fine (return time sum correctly within a week).

$billable_data = Project::where(['active' => 1, 'company_id' => session('company_id'), 'is_deleted' => 0])
        ->join('timelogs','timelogs.project_id','=','projects.id')
        ->select(DB::raw('(SELECT SUM(TIMESTAMPDIFF(second, start_time, end_time))  FROM timelogs WHERE timelogs.created_at BETWEEN "'.$monday.' 00:00:00" AND "'.$friday.' 23:59:59" AND  projects.billable = 0 GROUP BY projects.id) as non_billable_hours,
            (SELECT SUM(TIMESTAMPDIFF(second, start_time, end_time))  FROM timelogs WHERE timelogs.created_at BETWEEN "'.$monday.' 00:00:00" AND "'.$friday.' 23:59:59" AND  projects.billable = 1 GROUP BY projects.id) as billable_hours'))
        ->first()->toArray();


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

mercredi 15 décembre 2021

laravel and firebird connection

I'm traying to connecto to database with firebird and laravel 5.6. My firebird version is 2.5

I'm using this library:

https://github.com/harrygulliford/laravel-firebird

I can connect with flamebird. My database on the same lan network but in another server.

In library say that use env variables:

#FIREBIRD_HOST=OMEGA
#FIREBIRD_DATABASE=EMPRE001
#FIREBIRD_PORT=3050
#FIREBIRD_USERNAME=Grupo17
#FIREBIRD_PASSWORD=5468
#DB_FIREBIRD_CHARSET=ISO8859_1
#DB_VERSION=2.5

In my database.php file y have this:

'firebird' => [
            'driver'   => 'firebird',
            'host'     => env('FIREBIRD_HOST', 'localhost'),
            'port'     => env('FIREBIRD_PORT', '3050'),
            'database' => env('FIREBIRD_DATABASE', '/path_to/database.fdb'),
            'username' => env('FIREBIRD_USERNAME', 'sysdba'),
            'password' => env('FIREBIRD_PASSWORD', 'masterkey'),
            'charset'  => env('DB_FIREBIRD_CHARSET', 'UTF8'),
            'version'  => env('DB_VERSION', '2.5'), // Supported versions: 2.5, 1.5
            'role'     => null,
        ],

But I can't connect to my database and I don't know why. I'm trying to connect directly with:

'firebird'  => [
            'driver'    => 'firebird',
            'host'      => 'OMEGA',
            'port'      => '3050',
            'database'  => 'EMPRE001',
            'username'  => 'Grupo17',
            'password'  => '5468',
            'charset'   => 'ISO8859_1',
            'version'   => '2.5',
        ],

And I always get this return message:

[2021-12-15 15:57:56] local.ERROR: could not find driver (SQL: select

The model that I'm using to connect to firebird database is this:

protected $connection = 'firebird';

    protected $table = 'CONTRATOS';

    public $dateFormat = 'Y-m-d';

    public $incrementing = false;

    protected $dates = [
        'FECHA'
    ];

    protected $primaryKey = 'ID_CONTRATOS';

But it always returns this message and I don't know how I can continue.

Thanks for reading my question and helping.



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

mardi 14 décembre 2021

Javascript POST via fetch() not being received by Laravel Request?

I have a Javascript POST in the browser sending data to a Laravel (v5.4) backend. Network tab in the browser shows data sent successfully. Laravel logs show no data received. Can't see why...

Client:

fetch('saveloaddata', {
    method: 'POST',
    headers: { 'X-CSRF-TOKEN': $('#IDform > input[name="_token"]').val() },
    body: JSON.stringify(sendData),
    keepalive: true // Ensures data gets sent even after the page closed, see https://web.dev/disallow-synchronous-xhr/#fetch-keepalive
    });

Server: web.php

Route::post('saveloaddata', ['middleware' => 'auth', 'uses' => 'MainController@saveloaddata']);

MyController.php

public function saveloaddata(Request $request)
    {
    Log::info($request->all());

Log output is: local.INFO: array ()

Data being sent is just a short JSON string. On the client in the fetch() block I've also tried without JSON.stringify, so body: sendData, - same result.

POST requests to the same URL using JQuery $.ajax() work fine. I need to use fetch() for this though because this call is to send a small amount of data (~1 - 2 Kb) when the user closes the browser, so I'm following accepted practices (responding to a visibilitychange event in the browser and I would be using navigator.sendBeacon but that uses fetch() and I needed to set keepalive:true so am just using fetch() directly).

The request is clearly getting through Laravel's auth layer as the receiving function is triggered and the logging command runs (as do others in the same code, e.g. logging the user is fine). So, what has happened to the POST data!?

Thanks



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

Upgrade to Laravel 6 - Uncaught Error: Class 'Request' not found in app/Exceptions/Handler.php

I am currently upgrading from L5.8 to L6. I have read over the upgrade docs and made changes where necessary, if any. Once I changed the composer.json version to ^6.0 and ran composer update, I am getting the following stack trace.

This is on macOS running php 7.4

composer update
Loading composer repositories with package information
Updating dependencies
Nothing to modify in lock file
Installing dependencies from lock file (including require-dev)
Nothing to install, update or remove
Package jakub-onderka/php-console-color is abandoned, you should avoid using it. Use php-parallel-lint/php-console-color instead.
Package jakub-onderka/php-console-highlighter is abandoned, you should avoid using it. Use php-parallel-lint/php-console-highlighter instead.
Package swiftmailer/swiftmailer is abandoned, you should avoid using it. Use symfony/mailer instead.
Package fzaninotto/faker is abandoned, you should avoid using it. No replacement was suggested.
Package phpunit/php-token-stream is abandoned, you should avoid using it. No replacement was suggested.
Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover
PHP Fatal error:  Uncaught Error: Class 'Request' not found in /Users/ryahn/Public/Sites/alphacoder/rework/app/Exceptions/Handler.php:43
Stack trace:
#0 /Users/ryahn/Public/Sites/alphacoder/rework/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(376): App\Exceptions\Handler->report(Object(Symfony\Component\Debug\Exception\FatalThrowableError))
#1 /Users/ryahn/Public/Sites/alphacoder/rework/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(141): Illuminate\Foundation\Console\Kernel->reportException(Object(Symfony\Component\Debug\Exception\FatalThrowableError))
#2 /Users/ryahn/Public/Sites/alphacoder/rework/artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#3 {main}
  thrown in /Users/ryahn/Public/Sites/alphacoder/rework/app/Exceptions/Handler.php on line 43

Fatal error: Uncaught Error: Class 'Request' not found in /Users/ryahn/Public/Sites/alphacoder/rework/app/Exceptions/Handler.php:43
Stack trace:
#0 /Users/ryahn/Public/Sites/alphacoder/rework/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(376): App\Exceptions\Handler->report(Object(Symfony\Component\Debug\Exception\FatalThrowableError))
#1 /Users/ryahn/Public/Sites/alphacoder/rework/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(141): Illuminate\Foundation\Console\Kernel->reportException(Object(Symfony\Component\Debug\Exception\FatalThrowableError))
#2 /Users/ryahn/Public/Sites/alphacoder/rework/artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#3 {main}
  thrown in /Users/ryahn/Public/Sites/alphacoder/rework/app/Exceptions/Handler.php on line 43
Script @php artisan package:discover handling the post-autoload-dump event returned with error code 255

This is the Handler.php file its referencing to

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\Log;
use Request;
use Symfony\Component\HttpKernel\Exception\HttpException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        if ($exception instanceof HttpException === false) {
            $request = Request::all();
            Log::info("Error on page: " . Request::url());
            Log::info("Request data: " . htmlspecialchars(json_encode($request)));
        }

        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }
}

line 43: $request = Request::all();

I have tried to run php artisan config:cache and php artisan config:clear but still get the following stack trace.

I am most likely focusing on the wrong part of the stack trace. Hopefully its not something obvious I am over looking.



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

I can't start laravel application after update php to 7.4.26 [duplicate]

I was using Laravel 5.4 with PHP 5.6 and the application was working fine, but then I updated the PHP version to 7.4.26 and now the application only shows me a PHP file:

<?php

use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request;

define('LARAVEL_START', microtime(true));

/*
|--------------------------------------------------------------------------
| Check If The Application Is Under Maintenance
|--------------------------------------------------------------------------
|
| If the application is in maintenance / demo mode via the "down" command
| we will load this file so that any pre-rendered content can be shown
| instead of starting the framework, which could cause an exception.
|
*/

if (file_exists(__DIR__.'/../storage/framework/maintenance.php')) {
    require __DIR__.'/../storage/framework/maintenance.php';
}

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| this application. We just need to utilize it! We'll simply require it
| into the script here so we don't need to manually load our classes.
|
*/

require __DIR__.'/../vendor/autoload.php';

/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request using
| the application's HTTP kernel. Then, we will send the response back
| to this client's browser, allowing them to enjoy our application.
|
*/

$app = require_once __DIR__.'/../bootstrap/app.php';

$kernel = $app->make(Kernel::class);

$response = $kernel->handle(
$request = Request::capture()
)->send();

$kernel->terminate($request, $response);

I have tried some settings from the .htaccess and composer.json file but have not been successful. I have also updated with composer update but it has not worked.

In addition, I created a clean Laravel application to know if at least the page that Laravel brings by default would appear, but a PHP file always appears (In other attempts to configure it, it has shown me the content of the server.php file).



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

How to write correct way of sql query in php laravel

I want to fetch all data from this table for that i am using query :

      $emp = Employee::where('user_id', '=', $user->id)->first();

    $holidays = Holiday::orderBy('holidays.id', 'desc')->take(5)->where('holidays.id', '=', $emp->id)->get();

It is not giving me any result. I am new to php can anyone help me out yrr?

Holiday Table



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

lundi 13 décembre 2021

When i run the site in subdomain, i need to declare that subdomain in the .env file

Install is ok. But looks like you are running the site under subdomain. When you run the site in subdomain, you need to declare that subdomain in the .env file

IGNORE_SUBDOMAINS="www,menu"

iam using Larvel and my .env looks like this

APP_LOG_LEVEL=debug
APP_URL=https://menu.bethello.com/
APP_LOCALE=en
IGNORE_SUBDOMAINS=menu.bethello.com
TIME_ZONE="America/New_York"
CASHIER_CURRENCY=USD


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

yarn don't build public folder correctly

Recently I created a new Branch and when I was installing dependencies and building the project this error occurs:
enter image description here
My public folder was not builded correctly(I'm using yarn watch). Soo what I should do? I don't touch in my public folder and my webpack it wasn't too.



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

samedi 11 décembre 2021

Cant get proper data in Controller Laravel belongsToMany Relation - Laravel / Eloquent

A user(employer) have many posts and many user(employee) can apply these posts . Point is employer should get which users applied for each its posts.

I tried $employees = Post::find(//anyNumber//)->people; it gives proper applicants infos but it should be dynamic for each employer user .

Tables..

applies   ->  | users_id(employee) | posts_id |
posts     ->  | id                 | user_id(employer)  | (other posts cols ... )
user_info ->  | id                 | (name col  etc... for employee)

Post Model..

public function people()
{
   return $this->belongsToMany(Info::class , 'applies', 'user_id' , 'posts_id');
}

Controller..

public function index()
{
    $user_id = Auth::id();
    $myPosts = Post::where('user_id',$user_id)->get();
    $employees = Post::find(//anyNumber//)->people; // this line

    dd($employees);
}


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

vendredi 10 décembre 2021

Laravel Storage File not downloading (File not found)

in my laravel project i have uploads folder from where i am trying to download file.

Folder Hierarchy:

-Project
--Public
---Storage (created using php artisan storage:link)
----uploads
-----file.jpg ( i am trying to download)

Controller:

public function getdata(Request $request)
    {
        return Storage::download('/storage/uploads'.$image_name);
    //image name is file.jpg
      }

Error:

File not found at path: storage/uploads["file.jpg"]


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

Laravel SFTP Connection Using Passphrase

       This is the stand way that I have been using to place a file in SFTP 

Storage::disk()->put($fileName, file_get_contents($storagePath . $fileName));

But I am facing a situation where for connection first I need pass the key-phrase and post that only SFTP will askfor user_id and password,

How can Is set this up for Jobs in Laravel, Using Laravel 5.1 (due to some issues cant upgrade but that's not the concern as of now)

My Configuration in Filesystem

'new_sftp' => [
        'driver'     => 'sftp',
        'host'       => 'homestead',
        'port'       => 22,
        'username'   => 'myuser',
        'password'   => 'mypass',
        'root'       => /myroot/folder,
        'privateKey' => '/home/myroot/myfile.pem',
        'password'   => 'mypassprase',
        'timeout'    => '300',
        'visibility' => 'public',
        'permPublic' => 0766,
    ],


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

jeudi 9 décembre 2021

Route is working when referred but when I go to that provided link it will not find the controller function in laravel

I have added a custom function to save pictures and added the route as well and when I reference the route it does work but when visiting it gives error that the function can not be found with reflectionexception error ReflectionException

Function () does not exist

Controller ----------------------

/**
*    show the form for uploading profile picture 
*    
*   @return \Illuminate\Http\Response 
*/
public function changePicture()
{

    return view('usersinformation.profilepicture');
}

route web.php ---------------------------

Route::get('usersinformation/changePicture',[usersinformationController::class, 'changePicture'])->name('usersinformation.changePicture');

Route::post('usersinformation/savePicture', 'usersinformationController@savePicture');



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

Route issue in Laravel with several controllers and different route with same name

I have added below routes in web.php but it's not working.

Route::post('show', [
'as' => 'usersinformation.show',
'uses' => 'usersinformationController@show'


 ]);



 Route::post('store', [
    'as' => 'usersinformation.store',
    'uses' => 'usersinformationController@store'
  ]);



 Route::get('store',[usersController::class, 'store'])->name('usersinformation.store');
    Route::post('/store', 'usersController@store');
    Route::post('store',[usersController::class, 'store'])->name('users.store');
    Route::get('/index', 'usersController@index');

my controller is as below and I am using Ajax to send data but the error I receive is Method not allowed exception.

public function store(Request $request)
{
    //
    $fname = $request -> fname;
    $lname = $request -> lname;
    $pnumber = $request -> pnumber; 

    
}

Ajax Code ----------------

data = {
    _token: $('input#usersinformation-token').val(),
    'fname': $('input#first_name').val(), 
    'lname': $('input#last_name').val(),
    'pnumber': $('input#phonenumber').val()

};
$.post(url, data, function(data, status){
    alert('working' + data + "    " + status );
    $('div#load-content').html(data);
} );


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

mercredi 8 décembre 2021

Laravel, passing parameters to livewire form view give syntax error

I have this route:

Route::get("/bourse/add/{user}", function (User $user) {
     return view("bourse.new")->with('user', $user);    
})->name("bourse-add");

My new.blade.php file loads the form with livewire. according to the documentation (https://laravel-livewire.com/docs/2.x/rendering-components), I can insert my user id as a parameter like this:

<x-app-layout>
    <x-slot name="header">  </x-slot>
    @livewire('bourse.form', ['id'=> $user->id])
</x-app-layout>

but, however it is functional and the object "bourse" created is well assigned to my user, the comma is refused by IDE and therefore my parameter which comes after.

public function mount($reference = '', $id = null){
     if (!is_null($id)){
          $this->id_user=$id;
     }else{
          $this->id_user = Auth::id();
     }
    ...

have you had this problem and is there any other syntax that is not reported as error?



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

Primary Key is different from the default id that laravel searches for

I have added a custom primary key within the table and now the Laravel is not even finding the result at all. giving error that the page could not be found.

NotFoundHttpException

No query results for model [App\usersinformation].

Controller --------------------

public function show(usersinformation $usersinformation)
{
    //
  //  $users =  $user = usersinformation::where('user-id','=',$usersinformation) -> first();
    
        return view('usersinformation.show');

}

Model -------------------

class usersinformation extends Model
{
    //

    public $table = "usersinformation";
    public $incrementing = false;
    
    protected $fillable = [

        'fname','lname', 'user-picture', 'phone-number', 'user-id', 'place-id'

    ];
    protected $primaryKey = 'user-info-id';

    public function users(){
        $this -> belongsTo('App\users');
    }

route ---- web.php

Route::post('/show','App\Http\Controllers\usersinformationController@show');

Still facing the same issue, if I comment the primary key, it will give error that the id field is not found within the table when I add the custom primary key in the model, it will give error page not found.



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

How to join Multiple databases from different hosts in Laravel

Is there any way to use join query with Multiple databases from different servers?

my database.php is

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'db1'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            ...
        ],

        'mysql2' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST_2', '192.233.****.*'),
            'port' => env('DB_PORT_2', '3306'),
            'database' => env('DB_DATABASE_2', 'db2'),
            'username' => env('DB_USERNAME_2', 'root'),
            'password' => env('DB_PASSWORD_2', ''),
         ...
        ]

and i need to implement it in join query.

My controller function is

public function function1(){
$db1 = DB::connection('mysql2');
$result = TABLE1::join($db1 . '.' . 'table2', 'table2.id','=','table1.table2_id');

return Datatables::of($result);

}


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

mardi 7 décembre 2021

How to set the primary key itself as a foreign key in laravel?

This sounds nooby but I wanted to know if I can make the primary key work as a foreign key in Laravel, and I'am new to Laravel.

So, I have two migrations 'User' and 'Student' as Shown below: User :

 Schema::create('users', function (Blueprint $table) {
            $table->string('uniqueId', 30)->primary();
            $table->text('password');
            $table->string('userType');
            $table->timestamps();
        });

and Student :

Schema::create('students', function (Blueprint $table) {
            $table->string('uniqueId', 30)->primary();
            $table->text('name');
            $table->text('fName');
            $table->text('mName');
            $table->text('addr');
            $table->string('image');
            $table->integer('class');
            $table->integer('roll');
            $table->string('year');
            $table->timestamps();
        });

So, all I wanted was that the primary key in Student (uniqueId) also work as a foreign key that references the 'uniqueId' column from the User table.

Thanks in advance.



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

Laravel 5.2 New schedule entries not running on production

I have three command AAA, BBB and CCC.

CCC is the latest command that I have entered in this schedule, strange scenario is that AAA and BBB are still running as they were, but not CCC.

This laravel schedular runs all okay on local, but on production it is not showing any effect for CCC. Even doing php artisan ccc on production terminal works, but scheduler is showing no effect, no error for CCC.

Any idea what's causing it ? Is there any sort of cache or similar thing that is causing it ?

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        \App\Console\Commands\AAA::class,
        \App\Console\Commands\BBB::class,
        \App\Console\Commands\CCC::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('aaa')
                 ->hourly();

        $schedule->command('bbb')
                 ->everyTenMinutes();

        $schedule->command('ccc')
                ->everyTenMinutes();

    }

}


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

lundi 6 décembre 2021

Laravel command file output not updating

I updating Laravel command file.

File code updated on server but when I run command no changes in output.

how to update Laravel command file for new changes?



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

Pass a laravel variable into a jquery array

I am trying to pass a variable into a jquery autocomplete script check this url (https://jsfiddle.net/duoc5bbh/1/) I found.

Laravel

@foreach($data as $value)
   
   
@endforeach

Jquery

$(function() {
  let users = [{
      "email": "marie@gmail.com",
      "name": "marie"
      }, 
      {
       "email": "miss@gmail.com",
       "name": "miss"
     }];
});

what I did

$(function() {
  let users = [{
      "email": ,
      "name": 
      }];
});

I am new in using laravel with jquery I need your help in this Thanks.



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