vendredi 31 janvier 2020

Laravel 5.8: beberlei/assert/lib/Assert/functions.php return type produces error

I installed Laravel 5.8 on local server it works fine, but on remote server it reports the error

Parse error: syntax error, unexpected ':', expecting '{' in /***/vendor/beberlei/assert/lib/Assert/functions.php on line 37

This is the line producing the error

function that($value, $defaultMessage = null, string $defaultPropertyPath = null): AssertionChain
{
    return Assert::that($value, $defaultMessage, $defaultPropertyPath);
}

I think the PHP version can't understand the return type or Scalar type string. The PHP version of the server is 7.3.13 and return type and scalar type sting are valid statement in this version but it still reports the error. Do any of you guys know why does this happen?

Thanks in advance



via Chebli Mohamed

Migrations in Laravel 5+

Is there a way to execute migrations on laravel application in order to update current database structure? I use mysql database. I tried to execute

php artisan migrate:fresh

but it destroys and recreate the whole database structure. How do I avoid it?



via Chebli Mohamed

What guard does laravel uses by default for authentication user in LoginController and RegisterController?

I have made a simple authentication with default laravel configurations. My default guard is set to web guard.

 'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

My authentication works perfectly. Now when I put this route.

 Route::group(['middleware' => ['auth']], function () {

    // Users
    Route::get('users/me', 'UserController@me')->name('users.me'); 

   //...below routes.

This route is returning the exception unauthenticated. But when I pass the guard as auth:api here in the middleware, it works. So I just want to know over which guard was my user authenticated. Since default is mentioned is web and I have not added guard() method on laravel to change the guard, why it was not taking the default web one? Is it because it is mentioned in the api routes? And if it is so, how come does it work with auth:api anyway when I have not authenticated my user over that guard.



via Chebli Mohamed

SQl queries are throwing error maria Db Offset Problem laravel php

Recently I have deleted my vendor folder and reinstalled. After that change my all get queries are throwing error. I have no clue what i am missing.

Thanks

/Error/ SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'offset 0' at line 1

My Code:

public function couponList(Request $request){
        $sort_by = $request->get('sort-by');
        $order_by = $request->get('order-by');
        $homeTitle = 'Coupons and List'; 
        $coupons = DB::table('sb_coupons AS CO')
        ->select('CO.*','CO.status as couponStatus','CO.created_at as couponOrderDate','UT.*',
        'UT.firstname as userName')
        ->leftJoin('sb_customer AS UT', 'UT.customer_id', '=', 'CO.user_id');
        if(!empty($request->s)){
            $coupons->Where('CO.coupon_code', 'like', '%' . $request->s . '%');
        }
        if ($request->has('status')) {
            $coupons->where('CO.status', $request->status);
        }
        $coupons = $coupons->paginate(env('RECORD_PER_PAGE'));              
        $coupons->appends($request->s); 

        return view('admin.coupons.coupon-list',array('homeTitle'=>$homeTitle,'coupons'=>$coupons,'params'=>$request, 'sort_by'=> $sort_by , 'order_by' => $order_by))
        ->with('i', ($request->input('page', 1) - 1) * env('RECORD_PER_PAGE'));
    }

***.env *

APP_NAME=DeliverMyOrders
APP_ENV=local
APP_KEY=base64:LiLofkwJXFVZd4ZeUvGz/UADUFOeqx+Yeqv7L1gBHvY=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=delivermyorders
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
RECORD_PER_PAGE=10

FACEBOOK_ID=458516817946384
FACEBOOK_SECRET=9660233aee1cf8b443e4586ea864ea1a
FACEBOOK_URL=http://localhost:8000/auth/facebook/callback/


GOOGLE_ID=1512483269952
GOOGLE_SECRET=AIzaSyB-AiSA4Kd-R36M6J7NSTXxAWbVs7z4C_s
GOOGLE_URL=http://localhost:8000/auth/google/callback


via Chebli Mohamed

AdonisJS - SyntaxError. Unexpected character ' '

I am trying to fetch all talent resource from the database but when I tried the endpoint on Postman, it returned a SyntaxError. Unexpected character '' error. I dont know where that character is coming from as postman hinted that the error is on Line 66 of my controller, but on checking the line 66 is an empty/blank line. What could possibly cause this error? My controller code (the method the API is calling is below)

async searchTalent({ request, response }) {
        try {
            const params = request.except('projectId');
            let matchedTalents = [];
            let talentIds = [];
            const {tools, fullname} = params;

            if(tools) {
                const find = await Database.raw("SELECT * FROM pro WHERE MATCH tools AGAINST ('"+ tools +"' IN NATURAL LANGUAGE MODE)");
                const talents = find[0];
                if(talents) {
                    for(let t = 0; t < talents.length; t++) {
                        const talent = talents[t];
                        if(talent.active == true) {
                            const user = await User.query().where({id: talent.userId, active: true, type: 'talent', isDeleted: false}).first();

                            if(user) {
                                if(talentIds.length > 0) {
                                    if(talentIds.includes(talent.id) === false) {
                                        user.profile = talent;
                                        talentIds.push(talent.id);
                                        matchedTalents.push(user);
                                    }
                                } else {
                                    user.profile = talent;
                                    talentIds.push(talent.id);
                                    matchedTalents.push(user);
                                }
                            }
                        }
                    }
                }
                // for (let i = 0; i < tools.length; i++) {
                //  const tool = tools[i];
                // }
            } else if(fullname) {
                const getUsers = await User.query().where('first_name', 'LIKE', '%%' + fullname + '%%').orWhere('last_name', 'LIKE', '%%' + fullname + '%%').where({ active: true}).orderBy('id', 'desc').get();

                for (let i = 0; i < getUsers.length; i++) {
                    const user = getUsers[i];
                    if(user.type == 'talent')
                    {
                        const talent = await Pro.query().where({userId: user.id}).first();

                        if(talent)
                        {
                            user.profile = talent;
                            matchedTalents.push(user);
                        }
                    }
                }
            }
​
            const data = matchedTalents;
​
            return response.json({
                data: data,
                message: data.length + ' Talents fetched',
                error: false
            })
        } catch (e) {
            Event.fire('log::error', e.message)
            return response.json({
                data: [],
                message: e.message,
                error: true
            })
        }
    }

I have tried searching and fixing since yesterday but all stackoverflow answers don't seem to address this issue.



via Chebli Mohamed

Laravel add user via admin panel

my goal is add users by myself via admin panel. A form for entering the name, email and password is created. Username, password and email are fields of the same table, is it possible for the form to allow add values via hidden inputs and insert them ​​into different table in the database? The values from hidden inputs will be constant, only in different table than the name, password and email values.



via Chebli Mohamed

Issue while trying to Login as admin laravel php

I am trying to setup my local debugging environment for laravel application.

Everything was working fine. Today I deleted my vendor folder and did composer install. First I started getting error payload is undefined.

After that I am not able to login in the application as admin. This was not happening earlier. I am not sure why this is throwing error.

username: admin@admin.com password: admin12345

in DB in hashed format: $2y$10$BgzkwksC4dl8i3IWBGBGLudU1BjvK1giWf7wZeQm7dSOoxkaXfIAG

Hash::check($request->password, $admin->password) is always returning false.

Here is my Code:

public function login(Request $request){ 
        $validation = Validator::make($request->all(), [            
            'email'     => 'required|email',
            'password'  => 'required|min:5',            
        ]);
        if ($validation->fails()) { 
            return redirect()->back()->withErrors($validation)->withInput($request->only('email', 'remember'));   
        } 
        $admin = Admin::Where('email',$request->email)->first();
        if($admin){
            if (Hash::check($request->password, $admin->password)) {
                Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember);
                    Session::put('admin', $admin);
                return redirect()->intended(route('admin.home'));
            }else{
                return redirect()->back()->withErrors(['Wrong password.'])->withInput($request->only('email', 'remember'));
            }
        }
    return redirect()->back()->withInput($request->only('email', 'remember'));

    }

/composer.json/

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.6.4",
        "laravel/framework": "5.4.*",
        "laravel/socialite": "^3.0",
        "laravel/tinker": "~1.0",
        "maatwebsite/excel": "~2.1.0",
        "mobiledetect/mobiledetectlib": "^2.8",
        "nesbot/carbon": "^1.22",
        "pear/http_request2": "^2.3",
        "wildbit/laravel-postmark-provider": "^3.0",
        "wildbit/postmark-php": "^2.5",
        "vanderlee/swaggergen": "^2.3.19"
    },
    "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
    }
}


via Chebli Mohamed

Laravel do i need two controllers to handel two store functions?

Basically what i want to do is that 1 Controller handels two store functions called like this:

public function singleupload(){

..some code
}

and

public function multiupload(){
..some code too
}

as i continued to define the routes (get/post)

Route::get('/MultiUpload', 'controller@MultiUpload');
Route::get('/SingleUpload', 'controller@SingleUpload');

Route::post('/MultiUpload', 'controller@storeMulti');
Route::post('/SingleUpload', 'controller@storeSingle');

and as i tried to post some data to my database it tells me that there is no 'store' function. So i opened the docs and found this:

POST    /photos store   photos.store

So my question is can i create two store functions in one controller or do i have to create a different one so every route has its own controller with its own store function?



via Chebli Mohamed

PHP set empty field in database to value

My goal is set value if field is empty.

But get "Trying to get property of non-object" error.

last_day is empty field, how to assign value 1 ?

public function getPointsForExercises(){
        $ls = Auth::user()->lessons()->get();
        $last_day = Auth::user()->user_settings->last_day;
            if (empty($user->user_settings->last_lesson)) {
                $user->user_settings->last_lesson = 1; 
           } 


via Chebli Mohamed

jeudi 30 janvier 2020

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException thrown with message

I got this error when i tried to make a crud program on Laravel

Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException 
No message

my code :

public function update(Request $request){
DB::table('berita')->where('id_berita',$request->id)->update([
    'judul' => $request->judul,
    'isi_berita' => $request->isi,
]);
return redirect('/berita');
}

Help me to solve this T_T



via Chebli Mohamed

ErrorException controller@comment Not defined

My app in showing this error

Action App\Http\Controllers\ComplainController@comment not defined. (View: /var/www/html/Chirag_Laravel/resources/views/backend/pages/ifa/complaint.blade.php)

But i have already entered the controller and the route funtions properly

Controller part:

 public function comment($id,Request $request)
      {
        $user_name=$request->session()->get('user_name');
        $ticket=Complaint::Where('id','=',$id)
                ->SELECT('ticket_no')
                ->get();
        foreach($ticket as $tickets)
        {
         $tik=$tickets['ticket_no'];
          $comments=\DB::SELECT('SELECT comment,comment_by from comments where complaint_id=? AND comment_by=? or comment_by=? ORDER BY id DESC',[$tik,$user_name,'Admin']);
              return view('backend.pages.ifa.comment',compact('tik','id','comments','user_name'));
        }

      }
      public function getComment(Request $request)
      {
        $request->session()->put(['comment_success'=>'Comment Submitted Successfully']);
        $report_id=$request->session()->get('report_id');
        $complain=$request->get('tiko');
        $user_name=$request->get('user_name');
        $comment=$request->get('comment');
        //echo $complain_id."<br>".$comment;
        Comment::create(["complaint_id"=>"$complain","comment"=>"$comment","comment_by"=>"Bill"]);
        return redirect()->back();

      }

Route part:

Route::get('ifa-dashboard/comment/{id}',['uses'=>'ComplainController@comment']);
Route::POST('ifa-dashboard/getComment',['uses'=>'ComplainController@getComment']);

Blade part:

<td><center><a href="">Comment</a></center></td>

Cant find a way out



via Chebli Mohamed

Laravel's alias loader does not find class

We have a legacy project that we cannot update and we need to make some changes in symfony's Response.php in vendor. We have solved this by copying Response.php to a separate folder and using an alias to load that new class instead of vendor's. We did this in AppServiceProvider:

public function boot()
    {
        AliasLoader::getInstance()->alias('Symfony\Component\HttpFoundation\Response', 'App\Overrides\Response');
...

public function provides()
    {
        return ['Symfony\Component\HttpFoundation\Response'];

It worked fine until we pushed to production and suddenly it stopped working. While it still works fine on our dev servers. We can clearly see that the original class from vendor is being loaded instead of the one from Overrides so for some reason the alias doesn't work. Does anyone have any clue as to what could cause this? Don't even know where to start or what sorts of settings or artisan commands could have caused this behaviour.



via Chebli Mohamed

Laravel join from two tables including null

I have 3 tables listings, cities, state.

listings table:

id | city_id | state_id |...|

Listing model:

class Listing extends Model{

function city(){
    return $this->belongsTo('App\Models\City');
}

function state(){
    return $this->belongsTo('App\Models\State');
}

Listing migration:

public function up(){
    Schema::create('listings', function (Blueprint $table) {
        $table->integer('id')->unsigned()->index()->unique()->autoIncrement();
        $table->integer('city_id')->nullable();
        $table->integer('state_id')->nullable();
        ....

city_id/state_id is nullable !

cities table:

id | state_id | name | ...|

City Model:

class City extends Model{

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

    function state(){
        return $this->belongsTo('App\Models\State');
    }

Migration:

public function up(){
    Schema::create('cities', function (Blueprint $table) {
        $table->integer('id')->unsigned()->index()->unique()->autoIncrement();
        $table->integer('state_id')->nullable();
        $table->string('name');

states table:

id | name ...|

Model:

class State extends Model{

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

    function cities(){
        return $this->hasMany('App\Models\City');
    }

Migration:

public function up(){
    Schema::create('states', function (Blueprint $table) {
        $table->integer('id')->unsigned()->index()->unique()->autoIncrement();
        $table->string('name');

listings table has foreign keys to state_id and city_id. The relation for both is one city or state to many listings.

city table has foreign key state_id, too and relation one state to many cities.

I want to select everything from states and cities and count rows from listings table for each city/state, where I can:

foreach($listings as $listing){
    
}

I am using the latest Laravel version with MySQL.



via Chebli Mohamed

Get attribute from selected model

I am using PHP 7.1.33 and Laravel Framework 5.8.36.

I am getting a model back by name like the following Product::where('name', '=', $name)->get();

My Product model looks like the following:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'product';

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

When trying to get an attribute like the following I get an error:

$product = Product::where('name', '=', $name)->get();
$product->$url; // ERROR
$product->$category; // ERROR

Any suggestions how to access the attributes on my retrieved model?

I appreciate your replies!



via Chebli Mohamed

Pdf Report and Receipt generation in laravel 6.2?

Currently I am doing a project concerning student management..in my project there is features involve with payment of tuition fees and books sold to a student... What i need is to print receipt to both of them and generating a monthly and daily reports.. Can any one help which way or package should i use to perform those operations with print page of half A4 and good looking receipt? Help me!!
I tried on DomPdf but it failes to load grid system of bootstrap 4 and jimmy/laravel generator report it brings error on installing in laravel 6.2?



via Chebli Mohamed

Join and OrderBy within with laravel eloquent query

I want to display ordered list of stores based on cities from a brand.

This is the code I tried

 $brand = Brand::where('slug','=',$slugurl)
      ->with(['stores' => function($q){
        $q->where('status', 1)
        ->join('cities', function ($join){
              $join->on('cities.id', '=', 'stores.city_id')->orderBy('cities.sort_number', 'DESC');
        });

      }])
      ->firstOrFail();

The relationship of the tables :

Brand hasMany Stores and Stores belongTo Cities

The listings results output is not ordered based on cities sort_number. Any idea how to achieve this ?



via Chebli Mohamed

can someone teach me about this mock test step by s

the code

  1. How to make the "PodcastwasPurchased"?
  2. What is the output of this mocking test?


via Chebli Mohamed

LDAP Configuration Laravel5 - Authentication user provider [adldap] is not defined

I'm fresh beginner in Laravel 5.8 and i'm trying to develop an app with LDAP authentication.

I use this package : https://adldap2.github.io/Adldap2-Laravel/#/auth/setup

And i got this error : Authentication user provider [adldap] is not defined. Does anyone know this error and could tell me where my configuration can be wrong ?

Thansk for your help :)



via Chebli Mohamed

Redirect in Laravel .htaccess

I am beginner in Laravel. I use in my project Laravel 5.8. I make new website (old website was delete)

I have .htaccess:

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

    RewriteEngine On
    # Redirect to https
    RewriteCond %{SERVER_PORT} 80
    RewriteRule ^(.*)$ https://domain.pl/$1 [R,L]

    # Redirect to non www
    RewriteCond %{HTTP_HOST} ^www.domain.pl$ [NC]
    RewriteRule ^(.*)$ https://domain.pl/$1 [R=301,L]

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

    # Fonts
    # Add correct content-type for fonts
    AddType application/vnd.ms-fontobject .eot
    AddType application/x-font-ttf .ttf
    AddType application/x-font-opentype .otf
    AddType application/x-font-woff .woff
    AddType image/svg+xml .svg

    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/pdf "access plus 1 month"
    ExpiresByType text/javascript "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresByType application/x-javascript "access plus 1 month"
    ExpiresByType application/x-shockwave-flash "access plus 1 month"
    ExpiresByType image/x-icon "access plus 1 month"
    ExpiresByType image/ico "access plus 1 month"

    ExpiresByType text/css "access plus 1 month"
    ExpiresByType text/css "now plus 1 month"
    ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
    ExpiresByType application/x-font-ttf "access plus 1 month"
    ExpiresByType application/x-font-opentype "access plus 1 month"
    ExpiresByType application/x-font-woff "access plus 1 month"
    ExpiresByType image/svg+xml "access plus 1 month"
    ExpiresByType text/html "access plus 600 seconds"

    ExpiresDefault "access plus 2 days"

</IfModule>

This work fine.

I need add to this .htaccess:

  1. Redirect from https://domain.pl/oferta (error 404 - page not exist in new website) to https://domain.pl/oferta-2020 , https://domain.pl/kontakt to https://domain.pl/contact

  2. Redirect other error 404 to main page: https://domain.pl

How can I make it?



via Chebli Mohamed

mercredi 29 janvier 2020

ldap_sasl_bind showing Unknown authentication method in laravel

I am trying to implement LDAP in laravel 5.8 (PHP 7.2). I am getting issue while call ldap_sasl_bind method, its showing me error "Unknown authentication method".

I am able to login with LDAP admin with choosing option GSS-API and SASL.

Please help me to get resolve this issue.



via Chebli Mohamed

How to increase security of a Laravel site

I am a beginner in Laravel. I have a live project(ex:https://seniorcitizenhospital.com/) made with Laravel.

But while I use site::https://seniorcitizenhospital.com/ in google search engine for security checking it gives me a search result like below image

enter image description here

I can't understand how to remove these from my site.

Anybody Help Please? Thanks in advance



via Chebli Mohamed

Laravel resource route is not updating in database using

Laravel resource Route is not updating when i click update button, but it has store at same process.

I am using data-toggle="modal" for updating my value, but it is not update my category?

Where exactly my problem? i check my id is passed properly, but it is not going to my update controller function. i check using dd($request->all()); in my update function in controller.

my route is

Route::resource('/mother-category', 'MotherCategoryController');

my update and store function is

public function store(Request $request)
    {
        $validator =Validator::make($request->all(), [
            'mother_name' => 'required',

        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator);
        }

        MotherCategory::insert([
            'mother_name'=>$request->mother_name
        ]);

        return redirect()->back()->with('message','Mother Category Created Successfully');
    }



    public function update(Request $request, MotherCategory $motherCategory)
    {

        $motherCategory->update([
            'mother_name' => $request->mother_name
        ]);

        return redirect()->back()->with('message','Mother Category Updated successfully');
    }

and my blade file is


@extends('layouts.master')

@section('title', 'Add Mother Category')

@section('content')
    <div class="container">
        <div class="row">
            <div class="col-lg-10 mx-auto">
                <form action="" method="post">
                    @csrf
                    <div class="card">
                        <div class="card-header">
                            <h4 style="text-align: center">Add a mother category</h4>
                        </div>
                        <div class="card-body">
                            <div class="form-row mb-3">
                                <div class="col">
                                    <small class="text-uppercase text-dark">Mother Category<span
                                            class="required text-danger">*</span></small>
                                    <input type="text" id="mother_name" name="mother_name" class="form-control"
                                           placeholder="Mother Category" required>

                                    @if ($errors->has('mother_name'))
                                        <small
                                            class="form-control-feedback text-danger"></small>
                                    @endif
                                </div>
                            </div>
                            <div class="form-row mb-3">
                                <div class="col">
                                    <button type="submit" class="btn btn-success"><i class="fa fa-check"></i> Add
                                    </button>
                                    <button type="button" class="btn btn-inverse">Cancel</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        <br>

        <div class="row">
            <div class="col-md-12">
                <div class="card comp-card">
                    <div class="card-body">
                        <h5 class="w-100 text-center">All Mother categories</h5>
                        <div class="table-responsive">
                            <table class="table table-hover" id="motherTable">
                                <thead>
                                <tr>
                                    <th scope="col">#</th>
                                    <th scope="col">Name</th>
                                    <th scope="col">Action</th>
                                </tr>
                                </thead>
                                <tbody>
                                @foreach(App\Models\MotherCategory::all() as $index => $mc)
                                    <tr>
                                        <th scope="row"></th>
                                        <td></td>
                                        <td>
                                            <a href="#" class="btn btn-sm btn-info" data-toggle="modal"
                                               data-target="#exampleModalCenter">Edit</a>
                                            <a id="deleteBtn" data-id="" href="#"
                                               class="btn btn-sm btn-danger">Delete</a>
                                        </td>
                                    </tr>
                                    <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog"
                                         aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
                                        <div class="modal-dialog modal-dialog-centered" role="document">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title" id="exampleModalCenterTitle">Update</h5>
                                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                        <span aria-hidden="true">&times;</span>
                                                    </button>
                                                </div>
                                                <div class="modal-body">
                                                    <form action=""
                                                          method="post">
                                                        
                                                        
                                                        <div class="form-group">
                                                            <label for="exampleInputEmail1">Name</label>
                                                            "> --}}
                                                            <input name="mother_name" type="text" class="form-control"
                                                                   id="exampleInputEmail1" aria-describedby="emailHelp"
                                                                   placeholder="Enter mother category"
                                                                   value=""><br><br>
                                                            <input type="submit" class=" btn btn-success"
                                                                   value="Update">
                                                        </div>
                                                    </form>
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary"
                                                            data-dismiss="modal">Close
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection



@section('script')

    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.5/js/bootstrap-select.min.js"></script>

    <script>
        $('#motherTable').DataTable({

        });
    </script>

    <script>
        $(document).on('click', '#deleteBtn', function (el) {
            var mcId = $(this).data("id");
            swal({
                title: "Are you sure?",
                text: "Once deleted, you will not be able to recover this category!",
                icon: "warning",
                buttons: true,
                dangerMode: true,
            })
                .then((willDelete) => {
                    if (willDelete) {
                        swal("You have deleted a mother category!", {
                            icon: "success",
                        });
                        window.location.href = window.location.href = "mother-category/delete/" + mcId;
                    }


                });
        });

        $(document).on('click', '#deleteNo', function (el) {
            swal("Oops", "You can't delete this. Some item belongs to it!!", "error")
        })
    </script>
@endsection



via Chebli Mohamed

How Laravel Create a new Contract class file and Service class File

I want to create a member login for one portal to another. Currently I created a ProviderClass. So I am going to develop that as a service. In my laravel folder structure there is no any folder to 'Services' and 'Contracts'. How create a service and contract class.



via Chebli Mohamed

how can i submit the employee table id (auto increment) to the user table under the employee_id on form submit

public function store(Request $request)
{

     Employees::create([

        'first_name'=>$request['first_name'],
        'last_name'=>$request['last_name'],
        'email'=>$request['email'],
        'contact_no'=>$request['contact_no'],
        'join_date'=>$request['join_date'],
        'date'=>$request['date'],
        'employee_no'=>$request['employee_no'],
        'no'=>$request['no'],
        'profile'=>$request['profile'],
        'dob'=>$request['dob'],
        'leave_eligible_date'=>$request['leave_eligible_date'],
        'leave_eligible_date'=>$request['leave_eligible_date'],
        'employee_type_id'=>$request['employee_type_id'],
        'employee_designation_id'=>$request['employee_designation_id'],
        'employee_department_id'=>$request['employee_department_id'],
        'organization_hierarchy'=>$request['organization_hierarchy'],
        'direct_contact_person_id'=>$request['direct_contact_person_id'],
        'status'=>$request['status']
    ]);

i want to send the Employee table id to the user table under the employee_id column on form submit

      User::create([
        'name'=>$request['first_name'],
        'email'=>$request['email'],
        'photo'=>$request['profile'],   
        'employee_id'=>$request['????'], // i want send this line
        'password'=>Hash::make($request['password'])
     ]);
}

The above code will insert the data into two tables but i want the employee table id which is auto increment to be inserted into the user table under the employee_id column on form submit.



via Chebli Mohamed

Wrong object type: 7 ERROR: WITHIN GROUP is required for ordered-set aggregate mode in laravel

hello all I have a problem here message from sentry.io ERROR: WITHIN GROUP is required for ordered set set aggregate mode, I develop in production and production with the same code, in develop there are no problems that occur but in production there are errors like that Is it because of the database version difference or because my code has an error?

 $vendor  = DB::table('master.vendor_client as cv')
                    ->leftJoin('master.vendor as fv','fv.id','=','cv.vendor_id')
                    ->select('cv.*','fv.name','fv.mode','fv.vendor_type')
                    ->orderBy('cv.id')
                    ->get();   


via Chebli Mohamed

Not delete image from laravel backpack 4.0

I'm using image field in laravel backpack 4.0, it upload image without problems. When I delete it from 'delete button', it delete register, but not image file from my local folder. I'm checked the answer from backpack for laravel deleting image , but It no fix my issue.

My config/filesystem:

'disks' => [

    'local' => [
        'driver' => 'local',
        'root' => storage_path('app'),
    ],

    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],

    's3' => [
        'driver' => 's3',
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION'),
        'bucket' => env('AWS_BUCKET'),
        'url' => env('AWS_URL'),
    ],

],

My Model code:

public function setImageAttribute($value)
{
    $attribute_name = "image";
    $disk = config('backpack.base.root_disk_name'); // or use your own disk, defined in config/filesystems.php
    $destination_path = env('FOLDER_PUBLIC')."/uploads/medias"; // path relative to the disk above

    // if the image was erased
    if ($value==null) {
        // delete the image from disk
        \Storage::disk($disk)->delete($this->{$attribute_name});

        // set null in the database column
        $this->attributes[$attribute_name] = null;
    }

    // if a base64 was sent, store it in the db
    if (starts_with($value, 'data:image'))
    {
        // 0. Make the image
        $image = \Image::make($value)->encode('jpg', 90);
        // 1. Generate a filename.
        $filename = rand ( 10000 , 99999 ).'-'.strtolower(trim(preg_replace('/[\s-]+/', '-', preg_replace('/[^A-Za-z0-9-]+/', '-', preg_replace('/[&]/', 'and', preg_replace('/[\']/', '', iconv('UTF-8', 'ASCII//TRANSLIT', $this->title))))), '-')).'.jpg';

        // 2. Store the image on disk.
        \Storage::disk($disk)->put($destination_path.'/'.$filename, $image->stream());
        // 3. Save the public path to the database
        // but first, remove "public/" from the path, since we're pointing to it from the root folder
        // that way, what gets saved in the database is the user-accesible URL
        $public_destination_path = Str::replaceFirst(env('FOLDER_PUBLIC').'/', '', $destination_path);
        $this->attributes[$attribute_name] = $public_destination_path.'/'.$filename;
    }
}
public static function boot()
{
    parent::boot();

    static::deleting(function($obj) {

        \Storage::disk('public')->delete($obj->image);
    });
}

I have tried to change:

\Storage::disk('public')->delete($obj->image);

By:

\Storage::disk(config('backpack.base.root_disk_name'))->delete($obj->image);

But it not working too,

Can you help to me ?

Sorry for my english



via Chebli Mohamed

SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "user" does not exist in Laravel app

I did my research and none of the available solutions worked.

I am having the following issue:

SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "user" does not exist LINE 1: select * from "user" where ("email" = $1 or "user" = ... ^ (SQL: select * from "user" where ("email" = david.guzman@company.mx or "user" = david.guzman or "email" = david.guzman) and "user"."deleted_at" is null limit 1)

I am having this error only in my server. I have dropped the database, created and excecuted migrations, all the tables are created with their relations. I seed my database correctly and can even run queries in the psql terminal. User does exists, with all it's columns.

I did the same process in my local machine and it works perfectly. It actually started failing after y dropped the database and dropped the public schema and created it again. I think it may be a problem with postgres since it works on multiple computers.

None of the solutions I've looked up, has solved my issue.

Thanks!



via Chebli Mohamed

Remote DB host encountered error on Laravel

Please help! I want to connect to a database from a remote computer in Laravel but I'm getting error. I did every suggestions on google but still no luck. I can connect using Putty and can access through 192.168.9.204/phpmyadmin,

Here is my .ENV:

enter image description here

Database.php:

enter image description here

Error:

enter image description here



via Chebli Mohamed

UpdateOrCreate with model instance

I am using PHP 7.1.33 and Laravel Framework 5.8.36.

I am getting receiving data from a database row-by-row and I am creating a model using updateOrCreate() like the following:

foreach ($arr as $v) {

    $product = new Product();
    $product->name = $v['name'];
    $product->url = $v['url'];
    $product->price = $v['price'];

    // save
    $matchThese = ['name' => $name, 'url' => $url];
    $product->updateOrCreate($matchThese);
}

However, nothing gets created.

Any suggestions what I am doing wrong?

I appreciate your replies!



via Chebli Mohamed

How to send email by gmail in Laravel

how to send gmail email in larave, im very tired in this error, please help me

this is my .env file my env file

this is may error image email error



via Chebli Mohamed

Install mpdf or dompdf issue on laravel 5.2

I am trying to add dompdf on my laravel project using command-

composer require barryvdh/laravel-dompdf: 0.7.0

after installation i get error:

> [2020-01-29 17:45:54] local.ERROR: UnexpectedValueException: The > Response content must be a string or object implementing __toString(), > "boolean" given. in > D:\xampp\htdocs\mykidreport\vendor\symfony\http-foundation\Response.php:399 > Stack trace: > #0 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Http\Response.php(56): > Symfony\Component\HttpFoundation\Response->setContent(false) > #1 D:\xampp\htdocs\mykidreport\vendor\symfony\http-foundation\Response.php(201): > Illuminate\Http\Response->setContent(false) > #2 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Routing\Router.php(1085): > Symfony\Component\HttpFoundation\Response->__construct(false) > #3 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Routing\ControllerDispatcher.php(94): > Illuminate\Routing\Router->prepareResponse(Object(Illuminate\Http\Request), > false) > #4 [internal function]: Illuminate\Routing\ControllerDispatcher->Illuminate\Routing{closure}(Object(Illuminate\Http\Request)) > #5 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(52): > call_user_func(Object(Closure), Object(Illuminate\Http\Request)) > #6 [internal function]: Illuminate\Routing\Pipeline->Illuminate\Routing{closure}(Object(Illuminate\Http\Request)) > #7 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(102): > call_user_func(Object(Closure), Object(Illuminate\Http\Request)) > #8 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Routing\ControllerDispatcher.php(96): > Illuminate\Pipeline\Pipeline->then(Object(Closure)) > #9 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Routing\ControllerDispatcher.php(54): > Illuminate\Routing\ControllerDispatcher->callWithinStack(Object(App\Http\Controllers\DashboardController), > Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request), > 'index') > #10 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Routing\Route.php(174): > Illuminate\Routing\ControllerDispatcher->dispatch(Object(Illuminate\Routing\Route), > Object(Illuminate\Http\Request), 'App\Http\Contro...', 'index') > #11 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Routing\Route.php(140): > Illuminate\Routing\Route->runController(Object(Illuminate\Http\Request)) > #12 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Routing\Router.php(724): > Illuminate\Routing\Route->run(Object(Illuminate\Http\Request)) > #13 [internal function]: Illuminate\Routing\Router->Illuminate\Routing{closure}(Object(Illuminate\Http\Request)) > #14 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(52): > call_user_func(Object(Closure), Object(Illuminate\Http\Request)) > #15 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\View\Middleware\ShareErrorsFromSession.php(49): > Illuminate\Routing\Pipeline->Illuminate\Routing{closure}(Object(Illuminate\Http\Request)) > #16 [internal function]: Illuminate\View\Middleware\ShareErrorsFromSession->handle(Object(Illuminate\Http\Request), > Object(Closure)) > #17 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(136): > call_user_func_array(Array, Array) > #18 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline{closure}(Object(Illuminate\Http\Request)) > #19 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(32): > call_user_func(Object(Closure), Object(Illuminate\Http\Request)) > #20 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Session\Middleware\StartSession.php(64): > Illuminate\Routing\Pipeline->Illuminate\Routing{closure}(Object(Illuminate\Http\Request)) > #21 [internal function]: Illuminate\Session\Middleware\StartSession->handle(Object(Illuminate\Http\Request), > Object(Closure)) > #22 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(136): > call_user_func_array(Array, Array) > #23 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline{closure}(Object(Illuminate\Http\Request)) > #24 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(32): > call_user_func(Object(Closure), Object(Illuminate\Http\Request)) > #25 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse.php(37): > Illuminate\Routing\Pipeline->Illuminate\Routing{closure}(Object(Illuminate\Http\Request)) > #26 [internal function]: Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse->handle(Object(Illuminate\Http\Request), > Object(Closure)) > #27 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(136): > call_user_func_array(Array, Array) > #28 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline{closure}(Object(Illuminate\Http\Request)) > #29 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(32): > call_user_func(Object(Closure), Object(Illuminate\Http\Request)) > #30 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Cookie\Middleware\EncryptCookies.php(59): > Illuminate\Routing\Pipeline->Illuminate\Routing{closure}(Object(Illuminate\Http\Request)) > #31 [internal function]: Illuminate\Cookie\Middleware\EncryptCookies->handle(Object(Illuminate\Http\Request), > Object(Closure)) > #32 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(136): > call_user_func_array(Array, Array) > #33 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline{closure}(Object(Illuminate\Http\Request)) > #34 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(32): > call_user_func(Object(Closure), Object(Illuminate\Http\Request)) > #35 [internal function]: Illuminate\Routing\Pipeline->Illuminate\Routing{closure}(Object(Illuminate\Http\Request)) > #36 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(102): > call_user_func(Object(Closure), Object(Illuminate\Http\Request)) > #37 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Routing\Router.php(726): > Illuminate\Pipeline\Pipeline->then(Object(Closure)) > #38 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Routing\Router.php(699): > Illuminate\Routing\Router->runRouteWithinStack(Object(Illuminate\Routing\Route), > Object(Illuminate\Http\Request)) > #39 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Routing\Router.php(675): > Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request)) > #40 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(246): > Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request)) > #41 [internal function]: Illuminate\Foundation\Http\Kernel->Illuminate\Foundation\Http{closure}(Object(Illuminate\Http\Request)) > #42 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(52): > call_user_func(Object(Closure), Object(Illuminate\Http\Request)) > #43 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode.php(44): > Illuminate\Routing\Pipeline->Illuminate\Routing{closure}(Object(Illuminate\Http\Request)) > #44 [internal function]: Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode->handle(Object(Illuminate\Http\Request), > Object(Closure)) > #45 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(136): > call_user_func_array(Array, Array) > #46 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline{closure}(Object(Illuminate\Http\Request)) > #47 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(32): > call_user_func(Object(Closure), Object(Illuminate\Http\Request)) > #48 D:\xampp\htdocs\mykidreport\vendor\dingo\api\src\Http\Middleware\Request.php(111): > Illuminate\Routing\Pipeline->Illuminate\Routing{closure}(Object(Illuminate\Http\Request)) > #49 [internal function]: Dingo\Api\Http\Middleware\Request->handle(Object(Illuminate\Http\Request), > Object(Closure)) > #50 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(136): > call_user_func_array(Array, Array) > #51 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline{closure}(Object(Illuminate\Http\Request)) > #52 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(32): > call_user_func(Object(Closure), Object(Illuminate\Http\Request)) > #53 [internal function]: Illuminate\Routing\Pipeline->Illuminate\Routing{closure}(Object(Illuminate\Http\Request)) > #54 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(102): > call_user_func(Object(Closure), Object(Illuminate\Http\Request)) > #55 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(132): > Illuminate\Pipeline\Pipeline->then(Object(Closure)) > #56 D:\xampp\htdocs\mykidreport\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(99): > Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request)) > #57 D:\xampp\htdocs\mykidreport\public\index.php(53): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request)) > #58 {main}

and my composer.json file looks like this

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.2.*",
        "tymon/jwt-auth": "0.5.*",
         "dingo/api": "1.0.x@dev",
          "laravel/socialite": "^2.0",
        "webpatser/laravel-uuid": "2.*"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-root-package-install": [
            "php -r \"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"
    }
}


via Chebli Mohamed

Notification Laravel

i want to make notification in laravel using ajax and get data from controller but i don't know why this always said 500 internal server error

this is my ajax

$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  }
});
        $(document).ready(function(){
        // updating the view with notifications using ajax
        function load_unseen_notification(view = '')
        {
         $.ajax({
          url:"notif",
          method:"POST",
          beforeSend: function(xhr){xhr.setRequestHeader('X-CSRF-TOKEN', $("#token").attr('content'));},
          data:{view:view},
          dataType:"json",
          success:function(data)
          {
           $('.dropdown-menu').html(data.notification);
           if(data.unseen_notification > 0)
           {
            $('.count').html(data.unseen_notification);
           }
          }
         });
        }
        load_unseen_notification();
        setInterval(function(){
         load_unseen_notification();;
        }, 5000);
        });

controller

public function index()
{
    $pengumuman = Pengumuman::select("pengumuman.*")->count('pengumuman.id');
    $data = array(
        'unseen_notification'  => $pengumuman
    );
}

web.php

Route::Post('notif', 'NotifController@index')->name('notif');


via Chebli Mohamed

Laravel 5.8 - How to dump parameters from controller in the view

I'm fresh beginner in the PHP Framework Laravel (i'm using version 5.8), and i would like to dump all the variables of a controller from a view. Is that possible to do that ?

Thanks for your help :)



via Chebli Mohamed

Crawler + Guzzle: Accessing to modal popup values

I am new on LinkedIn and how to scrap modal popup values using Guzzle and crawler. enter code here $url1='https://www.linkedin.com/in/xxxxxxxxx/';$crawler1 = $client->request('GET',$url1);$crawler1->filter('.render-mode-BIGPIPE')->each(function ($node) use ($url1) {print $filternode=$node->text()."\n";});



via Chebli Mohamed

how to submit form Automatically, when it time is up?

Am trying to soft delete the post when the timeout, but unable to do that automatically..! Here's My Code:

@php
$date=str_replace('-', '/', $post->created_at);
$endDate=date('Y/m/d H:i:s',strtotime($date. ' + '.$post->post_days.' days'));
@endphp    
@if($endDate == 0)
<form action="">
<input type="text" name="postId" value="">
<button type="submit" >test</button>
</form>
@endif


via Chebli Mohamed

How can i write accessor methods for created_at or updated_at in Laravel 5.8?

I made two accessors like below code, but while fetching it is not showing what is being passed in accessors for created_at & updated.


    /**
     * This will change date according to timezone. 
     * @param String path
     */
    public function getCreatedAtAttribute($value)
    {
        return $this->changeDateFormUTCtoLocal($value);
    }

    /**
     * This will change date according to timezone. 
     * @param String path
     */
    public function getUpdatedAtAttribute($value)
    {
        return $this->changeDateFormUTCtoLocal($value);
    }

But this is not working. While other accessors are working which are following camelCase convention. Personally i assume it as an case issue. I think laravel assumes attributes as camelCase. What can be the solution ?



via Chebli Mohamed

laravel delete multiple record from different database at once

I want delete two record from different table with one delete function. however it is only deleting one of the record even though I passed two different Ids. this is my delete function

 public function delete($id){
   $user_id = auth() ->user()->id;
   $card =  Card::where('id', $id)->delete();
   $actCity = city::where('id', $id)->delete();

  return redirect('/home')->with('success', 'Post Removed');

this is my delete button

 @if (!empty($cardd && $actCity))
   {!!Form::open(['action'=>['PlanController@delete','id' =>$cardd[0], 'id'=>$actCity[0]],'method'=>'POST','class'=>''])!!}
   @endif
    
    {!! Form::submit('Delete', array(
        'class'   => 'btn btn-danger',
        'onclick' => "if( ! confirm('Are you sure you want to delete your 
 package?')){return false;}"
    )) !!}  {!! Form::close() !!}

my route

Route::delete('delete/{id}', 'PlanController@delete');


via Chebli Mohamed

Conflicts between boostrap css and tailwindcss in laravel 5.8

i have Installed la-ravel 5.8 with bootstrap. Then i installed tailwindcss and i tried using the prefix 'tw-' to separate the classes. After compiling npm run dev the page is not displaying properly because of the conflicts between the classes you used. How best can i handle this https://redesign-worklog.doegel.de/



via Chebli Mohamed

mardi 28 janvier 2020

laravel + react not loading React's stuff with localhost (without php artisan serve)

Is it possible to run Laravel + react with some thing like http://localhost/projectfolder/public

without php artisan server

Thanks



via Chebli Mohamed

Auditoria en laravel 5.8 [closed]

Cómo puedo automatizar el registro de actividades de un usuario en laravel?

Si un usuario ingresa a un app de laravel, debo guardar toda su actividas, a que páginas entra, si ingresa, edita o elimina un registro, cuales repirte visualiza

Todo lo que encuentro es laravel logging, pero dirigido a errores, no a actividad de los usuarios.



via Chebli Mohamed

Clear SessionStorage or localStorage after form submit not working

I am using laravel 5.5 created a quiz form where user can enter his answer and submit. user will have max duration when it reaches 0 the form will automatically submit. I used sessionStorage to store the timer so that the timer won't reset on page refresh, but the problem is sessionStorage is not clearing after the form submit.

<span id="divCounter" class="label label-success timer">00 Hrs : 00 Mins : 00 Secs</span>

<script type="text/javascript">
//Set Time To Session Storage
 if (sessionStorage.getItem("timerStorage<?php echo $singleData->id; ?><?php echo Auth::id(); ?>")) {
  if (sessionStorage.getItem("timerStorage<?php echo $singleData->id; ?><?php echo Auth::id(); ?>") == 0) {
  var timer = <?php echo $singleData->duration; ?>;
} else {
  var timer = sessionStorage.getItem("timerStorage<?php echo $singleData->id; ?><?php echo Auth::id(); ?>");
}
}else{
var timer = <?php echo $singleData->duration; ?>;
}
setInterval(
  function() {
    if(timer == 0) {
      sessionStorage.setItem("timerStorage<?php echo $singleData->id; ?><?php echo Auth::id(); ?>", 
<?php echo $singleData->duration; ?>);
    document.quizSubmit.submit();     
  } else {
    timer--;
    timeConvert(timer);
    sessionStorage.setItem("timerStorage<?php echo $singleData->id; ?><?php echo Auth::id(); ?>", timer);
  }
}, 1000);
function timeConvert(timer) {
var oldtime = timer;
var hours = Math.floor(timer / 3600);
var minutes = Math.floor(timer % 3600 / 60);
var seconds = timer % 3600 % 60;
if (hours   < 10) {hours   = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
document.getElementById('divCounter').innerHTML = hours + ' Hrs : ' + minutes + ' Mins : ' + seconds + ' Secs';
document.getElementById("myInput").value = timer;
}

//Clear Storage Session On Form Submit
$('#quizSubmitClear').submit(function(e){
  e.preventDefault();
  sessionStorage.clear(); 
});
 </script>


via Chebli Mohamed

How to make autofill into add/remove field dynamically using jquery?

I am doing a program using laravel. I use add/remove field with jquery. The first field grab the data from database to list out the person's name.

     <div class="container table-responsive col-lg-10">
          <form method="post" id="dynamic_form">
            <span id="result"></span>
             <table class="table table-hover table-responsive table-bordered" id="user_table">
           <thead>
            <tr>
                <td class="text-center col-lg-3">Nama</th>
                <td class="text-center col-lg-2">No Personal</th>
                <td class="text-center col-lg-1">Jabatan</th>
                <td class="text-center col-lg-1">Telefon</th>
                <td class="text-center col-lg-1">Ext</th>
                <td class="text-center col-lg-1">Action</th>
            </tr>
           </thead>
           <tbody>

           </tbody>
           <tfoot>
            <tr>
              <td colspan="2" align="right">&nbsp;</td>
              <td></td>
            </tr>
           </tfoot>
       </table>
    </div>  
    <script>
      $(document).ready(function(){

      var count = 1;

      dynamic_field(count);

      function dynamic_field(number)
      {
      html = '<tr>';
     html += '<td><select id="nama" name="nama[]" class="form-control"><option value="">--Pilih--</option><?php foreach($staff as $key => $value):echo '<option value="'.$key.'">'.addslashes($value).'</option>'; endforeach; ?></select></td>';
    html += '<td><input type="text" name="no_personal[]" class="form-control" /></td>';
    html += '<td><input type="text" name="jabatan[]" class="form-control" /></td>';
    html += '<td><input type="text" name="telefon[]" class="form-control" /></td>';
    html += '<td><input type="text" name="ext[]" class="form-control" /></td>';
    if(number > 1)
    {
        html += '<td class="text-center"><button type="button" name="remove" id="" class="btn btn-danger remove">Batal</button></td></tr>';
        $('tbody').append(html);
    }
    else
    {   
        html += '<td class="text-center"><button type="button" name="add" id="add" class="btn btn-success">Tambah Pegawai</button></td></tr>';
        $('tbody').html(html);
    }
}

   $(document).on('change', '.nama', function(){
    var staffID = jQuery(this).val();
    if(staffID)
    {
      jQuery.ajax({
          url : 'add_demo/get_staff/'+staffID,
          type : "GET",
          dataType : "json",
          success:function(data)
          {
            console.log(data);
                $('#no_personal').val(data.Nobadan);
                $('#jabatan').val(data.SectionID);
                $('#telefon').val(data.notelttp);
                $('#ext').val(data.ext);   
          }
      });
    }
    else
    {
      $('#no_personal').empty();
      $('#jabatan').empty();
      $('#telefon').empty();
      $('#ext').empty();
    }
  });


 $(document).on('click', '#add', function(){
  count++;
  dynamic_field(count);
  });

 $(document).on('click', '.remove', function(){
  count--;
  $(this).closest("tr").remove();
 });

});
</script>

When the first field(staff name)selected,the information about no_personal, jabatan, telefon and ext will be filled automatically into the field. The information grabbed using this ajax url:

 url : 'add_demo/get_staff/'+staffID,

The controller for that is:

$data = staffs::where('staffID', $staffID)
            ->select('staffs.No_pers', 'staffs.JabID', 'staffs.notel', 'staffs.ext')
            ->first();

return json_encode($data);

I can list out the staff name in the selection box. But when I selected the staff name, the information is not filled into the fields.

How to improvised the code? I tried to put id in the added fields, but it gives error of same id name for added fields.



via Chebli Mohamed

Multiple Request with Guzzle in Laravel

I've restapi with pagination and I need to combine the result for sitemap.

Json Results

    {
        ...
        "info": {
            "playlistId":"PLxxxxx",
            "totalResults": 242,
            "maxResults": 50,
            "nextToken": "CCAAQ"
        },
        "results": [
            {
                "id": 1,
                "title": "How to make a Cookies",
            }
            ...
        ]
    }

I've trying with below code, but still no luck. lot of duplicate video. I don't know what's wrong with this. I've try use promise too, but the results still duplicated.

            ...

            $requests = [];
            foreach ($playlists['playlistId'] as $playlistId) {
                if (!empty($playlistId)) {
                    $result = $client->request('GET', route('api.playlist', ['playlistId' => $playlistId]));
                    $guzzle = \GuzzleHttp\json_decode($result->getBody(), true);
                    ...
                    $pages = ceil($total_posts / $max_per_page);

                    for ($i = 0; $i <= $pages; $i++) {
                        $pageToken = Helper::youtubeToken();

                        $requests[] = new GuzzleRequest('GET', route('api.playlist', ['playlistId' => $playlistId, 'page' => $pageToken[$i]]));

                    }
                }
            }

            $responses = Pool::batch($client, $requests, array(
                'concurrency' => 1000,
            ));

            foreach ($responses as $response) {
                //do something
                $respon = \GuzzleHttp\json_decode($response->getBody(), true);

                if ($respon['info']['playlistId']) {
                    $filename = $respon['info']['playlistId'];
                    $nextToken = $respon['info']['nextToken'];
                    $sitemap = Sitemap::create();

                    foreach ($respon['results'] as $hasil) {
                        $slug = ApiController::make_slug($hasil['title']);
                        if (!empty($nextToken)) {
                            $sitemap->add();
                            ...                               

                        }

                    }
                    $sitemap->writeToFile("$playlistPath/$filename.xml");

                }

            }

I need to get all of the results list and filtered by playlistId.

Thanks in advance.



via Chebli Mohamed

How to call PHPCap external package in laravel 5.5

I need to use the below package in Laravel 5.5 it's an external package.

https://github.com/iuredcap/phpcap

I download zip from above the GitHub URL and phpcap directory added in Laravel 5.5 vendor folder.

and use below code and in my controller.

use \IU\PHPCap\RedCapProject;

OR

use IU\PHPCap\RedCapProject;

and Call below function in my action

$project = new RedCapProject($apiUrl, $apiToken);

But every time given below error.

Class 'IU\PHPCap\RedCapProject' not found


via Chebli Mohamed

Assert Laravel Command is Called in Test

I call Laravel commands from a Laravel command. It works, but I want to test if the subcommands A and/or B are called.

Below a simplified version:

final class HandleActions extends Command
{
    public function handle()
    {
        foreach ($items as $item) {
            if ($item->price * 2.24 > 100) {
                $this->call('order:reprocess'); // command A
            }

            if (!$item->stock) {
                $this->call('order:cleanup'); // command B
            }
        }
    }
}

I test this command like so (simplified), so I know that the main command is excited successfully.

    $this->artisan('command')->assertExitCode(0);
    // How do I assert command A is fired?
    // How do I assert command B is fired?

I want to assert that subcommand 1 is fired and/or subcommand 2 fired. But how to do this?



via Chebli Mohamed

Laravel - null value is returned from the database

I get "is null" value from column in database, how to figure out why ?

controler:

public function getValues(Request $request)
    $node_id = floor($day);
    $sub_id = $day;
    $mtime = $request->mtime;
    $silent_data = Auth::user()->lessons()->where('mtime',$mtime)->where('sub_id',$sub_id)->where('node_id',$node_id)->first();

table lessons:

id int(10)
user_id int(10)
node_id int(10)
sub_id varchar(191)
mtime int(10)

laravel console:

select * from `lessons` where `lessons`.`user_id` = 11382 and `lessons`.`user_id` is not null and **`mtime` is null** and `sub_id` = '1.4' and `node_id` = 1

table lessons column mtime has value 10



via Chebli Mohamed

UnexpectedValueException: The Response content must be a string or object implementing __toString(), "boolean" given

Getting error after installing dompdf

[2020-01-28 18:23:03] local.ERROR: UnexpectedValueException: The Response content must be a string or object implementing __toString(), "boolean" given. in D:\xampp\htdocs\myproject\vendor\symfony\http-foundation\Response.php:399



via Chebli Mohamed

How can I convert many statement mysql dinamis to laravel eloquent?

Mysql query like this :

SET @sql_dinamis = (
        SELECT
            GROUP_CONCAT( DISTINCT CONCAT('SUM( IF(id_barang=',id_barang,',jml_bk,0)) AS br',id_barang))
        FROM barang_keluar
    );

    SET @SQL = CONCAT('SELECT month(tgl_keluar) as m,',@sql_dinamis,' 
           FROM barang_keluar
           WHERE month(tgl_keluar) and year(tgl_keluar)=2019
           GROUP BY month(tgl_keluar)'
       );

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

I want to convert it to laravel eloquent, but i'm confused. Because there exist many statement. There exist PREPARE, EXECUTE, SET, DEALLOCATE etc. You can see query above

How can I convert it to laravel eloquent?



via Chebli Mohamed

Google Drive API list all occurances of the folder

I am using Google Drive API client for Laravel and I am trying to list the folders by query filters.

$scope = Config::get('options.gdrive_scopes');
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . base_path() . DIRECTORY_SEPARATOR . 'gdrive_atdnj.json');

$user = Config::get('options.google_drive_user_name');
$client = new \Google_Client();
$client->useApplicationDefaultCredentials();
$client->setApplicationName(Config::get('app.name'));
$client->setScopes($scope);
$client->setAccessType('offline');
$client->setSubject($user);

$service = new \Google_Service_Drive($client);
$files_to_be_uploaded = Storage::files('orders/' . $orderId);

$project_folder_filters = array(
 'fields' => 'files(id)',
 'q' => "name contains '" . $project_folder_name . "' and mimeType='application/vnd.google-apps.folder'",
 'supportsAllDrives' => true,
 'includeItemsFromAllDrives' => true,
);
 $project_folder_results =   $service->files;
 $project_folder_results = $service->files->listFiles($project_folder_filters);
 dd($project_folder_filters, count($project_folder_results->getFiles()));

In return I am getting only one One returned in result set occurrence of the folder where on Google Drive, there are 2 folders created with the same name 2 folders with same name. Thought the owner is different. How can I all the folders by the given querystring usng google drive API?



via Chebli Mohamed

Laravel 5 return redirect is not working as it should

I'm having a controller with some functions. In every function I get user data by sharing it from the Contoller.php

In controller.php

public function share_user_data() {
    $user = Auth::user();
    $this->checkValidation($user);
    $this->user = $user;
    View::share('user', $user);
}

public function checkValidation($user){
    if($user->email_activated == 0){
        var_dump($user->email_activated); // I get: int(0)
        return redirect('/verifyEmail');
    }
}

In the other controller

public function viewCategory(Category $category){
    $this->share_user_data(); // here's the check
    $this->get_site_lang();
    $products = $category->products;
    return view('category', compact('category','products'));
}

But I get the category view and not redirected to the verifyEmail route. How to fix this and why it's happening?



via Chebli Mohamed

How hard/easy is it to convert this to CodeIgniter 3?

I lately used FreeScout and think its "System Status" page is pretty neat. FreeScout Status Page Thats why I want to make my own for another project. As FreeScout is based on Laravel but the other project is based on CodeIgniter 3 where are some differences.

Also you should know I modified the Screenshot (deleted some parts which I do not need).

What would be required:

Info:

  1. TimeZone that is beeing used
  2. Protocol
  3. Web Server
  4. PHP Version

PHP Extension:

  1. gd
  2. hash
  3. json
  4. mbstring
  5. mysqli
  6. openssl
  7. recode
  8. xmlrpc
  9. zlib

Permission: (775)

  1. Folder Path 1
  2. Folder Path 2
  3. Folder Path 3

Cron:

  1. Last time run of cron

Do some of you guys already have some experience with creating "System Status" or "System Info" pages for CodeIgniter 3 or PHP 7 at all?



via Chebli Mohamed

Laravel migration fails with SQLSTATE[HY000]: General error: 1215

I'm trying to add a migration with laravel. This is mi migration file.

public function up() {
    Schema::create('sl_categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title')->nullable();
        $table->integer('user_id')->unsigned()->nullable();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->softDeletes();
        $table->timestamps();
    });

    Schema::create('sl_images', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('image')->nullable();
        $table->integer('sl_category_id')->unsigned()->nullable();
        $table->integer('display_order')->nullable();
        $table->softDeletes();
        $table->timestamps();
    });

    Schema::table('sl_images', function(Blueprint $table) {
        $table->foreign('sl_category_id')->references('id')->on('sl_categories')->onDelete('cascade');
    });
}

public function down() {
    Schema::dropIfExists('sl_images');
    Schema::dropIfExists('sl_categories');
}

But unfortunately I'm getting this error.

Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table sl_images add constraint sl_images_sl_category_id_foreign foreign key (sl_category_id) references sl_categories (id) on delete cascade)



via Chebli Mohamed

I'm using single ip with multiple port number for laravel frontend and backend. e.g 123.23.5.1:89 and 123.23.5.1:90

I just want know that how I can use Laravel asset() and url() function to return url with port number. currently both the function returns http://123.23.5.1

But I want full address like this http://123.23.5.1:89

Can you please help me?

Thanks in advance.



via Chebli Mohamed

How would I get no of sends & no of opens for push notification using FCM APIs?

I am sending push notification on Android & IOS app using FCM API of firebase which is https://fcm.googleapis.com/fcm/send When I send push notification from dashboard It gets received on user's mobile phone.

I wanted to keep track of no of sends & opens of push notification.

Thanks!



via Chebli Mohamed

Laravel: Login form "Remember Me" functionality not working

One of my website is developed in Laravel, it was working fine before. What does is I want to move website from beta.example.com to example.com so I have pointed to beta with original domain name(example.com).

The Website is working fine but all remember me functionality is not working. Now Users have to enter the password and also if they check the check box (remember me) still it does not store the password in cookies or session.

Please help me.

Thank you



via Chebli Mohamed

Trying to get property 'id' of non-object in demo.blade.php

Hi I am working on the checkout page in laravel and sent some product data from the cart to checkout and trying to print all the details from an json object but i keep getting the error as Trying to get property 'id' of non-object

The controller function is

public function bill(Request $request){

            $input = $request->all();

            return view('demo')->with('product' , $request->product)
                              ->with('subtotal' , round($request->subtotal));
        } 

the cart form is

<form method="post" action="">
                                

                                @foreach($cart as $product)
                                 <input type="hidden" name="product[]" value="">
                                @endforeach

                                <input type="hidden" name="subtotal" value="">
                                <button type="submit" class="gray_btn">Checkout</button>
                              </form></a>

the blade page is

@foreach($product as $input)





@endforeach

when i only print the input i am getting the result as

{"id":"10","name":"S007-4ft","price":40,"quantity":"102","attributes":{"image":"glassfilms\/December2019\/MyelERNBbAWhGRbKWiCK.jpg","crm":"PRO209"},"conditions":[]} {"id":"7","name":"Frosted 007-4ft","price":40,"quantity":"103","attributes":{"image":"glassfilms\/December2019\/ZJgWUNaYrPnvsoRfuagv.jpg","crm":"PRO105"},"conditions":[]} 

but when i try to print the id only using i am getting the error.

the route is

Route::post('pay', 'RazorpayController@bill')->name('pay');


via Chebli Mohamed

Display Laravel Notification (MailMessage) with markdown after sent

I'm saving every email I send to an entity into the database by creating a function storeEmail and make an insert using a model EmailMessage. Everything works fine, but the main goal is to display the message exactly as it was, when the recipient received and retrieve all the messages I sent as a User, to a page (something like Send page in Gmail).

This is my Notification class:

class SimpleEmail extends Notification
{
    use Queueable;

    private $link;
    private $user;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($link)
    {
        $this->link = $link;
        $this->user = Auth::user();
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {   
        $mail = (new MailMessage)
            ->from($this->user->email, $this->user->name)
            ->subject('My Dummy Subject')
            ->greeting('To: '.$notifiable->email)
            ->action('Action Button', url($this->link))
            ->line('Thank you for reading my message')
            ->salutation('Friendly, '.$this->user->name);

        $this->storeEmail($mail,$notifiable);
        return $mail;
    }

    public function storeEmail($mail,$notifiable){
        $email = new EmailMessage;
        $email->sender_type = 'App\User';
        $email->sender_id = $this->user->id;
        $email->mail = $mail;
        $email->save();
        $notifiable->email_messages()->save($email);
    }
}

Note:

  1. I'm using Illuminate\Notifications\Messages\MailMessage
  2. My class extends Illuminate\Notifications\Notification
  3. I'm saving (new MailMessage) in the $email->mail = $mail;

I tried to dd($email->mail); and I get this:

 ^ array:20 [▼
  "view" => null
  "viewData" => []
  "markdown" => "notifications::email"
  "theme" => null
  "from" => array:2 [▶]
  "replyTo" => []
  "cc" => []
  "bcc" => []
  "attachments" => []
  "rawAttachments" => []
  "priority" => null
  "callbacks" => []
  "level" => "info"
  "subject" => "My Dummy Subject"
  "greeting" => "To: Dohn John"
  "salutation" => "Friendly, Nikolas Diakosavvas"
  "introLines" => array:2 [▶]
  "outroLines" => array:1 [▶]
  "actionText" => "Action Button"
  "actionUrl" => "http://my-example-url.com ▶"

How can I display the Mail Notification, as it was when I sent it ? What is the optimal solution for that ? Thanks, in advance

EDITED

Managed to render MailMessage using this code works :

$email = EmailMessage::first();
return (new \App\Notifications\SimpleEmail('my-link', $email->recipient->assignto))->toMail($email->recipient);

But this is not exactly what I wanted, because every time I need to find:

  1. Which Notification class used on every email so I can render it.
  2. Variables for each Notification class.


via Chebli Mohamed

lundi 27 janvier 2020

Show name of fields in message in Input Array Validation in Laravel

I have array of dropdown with the same name what i'm trying to do is to display the actual name of the field when the error is displayed but now it is displaying like attributes.Size Attributes Fields are required but i want actual name which i am passing as a title to an array.

Code:

$validator = Validator::make($request->all(), [
 'attributes.*' => 'required',
 ],[
 'attributes.*.required' => ':attribute Attributes Fields are required.',
 ]);

 {!! Form::select('attributes['.$attr->title.']') !!}


via Chebli Mohamed

How to combine two sql table in laravel 5.8

I am trying to compare two tables to check is user data already exits in another table. I show some posts they talk about whereRaw but details is not enough i was try to run query but i am not getting which i want.

UPDATED I have 2 tables one is for challenges between two people

Challenge Table  id,user_one, user_two, data_one, data_two,winner_id

And my second table is

vote Table id, user_id, battle_id, voted_user

I want to check is user already votes the table or not, If yes skip that challenge table and show remain table data to user.

$challenges = DB::table('challenges')->whereRaw([
            ['challenges.user_one', '!=', $uid],
            ['challenges.id', '!=', 'vote.id'],
        ])->orWhereRaw([
            ['challenges.user_one', '!=', $uid],
            ['challenges.id', '!=', 'vote.id'],
        ])->get();


via Chebli Mohamed

Insert / update implode comma separated values in laravel

                      $value4_1=implode(',',$dff_value4).',';
                      $name5_1=implode(',',$dff_name5).',';
                      $value5_1=implode(',',$dff_value5).',';
                      $number1=implode(',',$sr_number).',';

how to write an update query in laravel controller to update these values in a table on $number1 basis , named masterdata, table fields are id,value4,name5,value5_1,number.

while print_r($dff_value5_1);

it showing like below

Browsing,All,All,Browsing,313131,754745645,All,Everywhere,9846098460,Everywhere,Particular



via Chebli Mohamed

Wrapping Vue entry point around blade produces a template warning

I have an existing Laravel app that I'm slowly replacing the sections of it into Vue.

Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>, as they will not be parsed.

Existing Laravel code in the Blade file with <div id="app"></div> wrapped around it for Vue entry point:

<div id="app>
  <div class="wrapper">
     <header>
        // content
     </header>
     @yield('content')
  </div>
</div>

The 'content' yielded is different blade files, depending on the tab clicked in the nav. I am assuming the warning is because the blade files yielded have JS at the bottom of them (eg: <script type="text/javascript"> code here</script> ).

I'm not sure if this warning is meaning that some code is not being run in the blade or not.



via Chebli Mohamed

Correct way to set up this Laravel relationship?

I'm after a bit of logic advice. I am creating a system where users login and register their participation at an activity. They can participate at an activity many times. What is the best way to do this? I want to ensure I can use eloquent with this rather than creating my own functions.

I am imagining...

Users:

id

Activitys:

id
name

Participations:

id
user_id
activity_id
time_at_activity

I want to later be able to do such things as: $user->participations->where('activity_id', 3) for example.

What is the best way to set this up? I had in mind..

User: hasMany->Participations

Activity: belongsTo->Participation

Participation: hasMany->Activitys & belongsTo->User

Does this look correct?



via Chebli Mohamed

Xero oAuth 2 authorisation in laravel

I have a Laravel PHP project application. The server creates an invoice on Xero and sends the user an email etc...

I have been using OAuth 1 (Private App - PHP SDK) with no issues, but now need to switch to OAuth 2. As there is no front end-user on the server, can this still be accomplished?

All the documentation I read, seems to need a manual login to grant authorization and get an access token?



via Chebli Mohamed

Problem to create a good SEO friendly route with Laravel

I have a SEO project with Laravel, I want to use the routes to config a friendlys dynamic urls. This is my route:

# Designs
    Route::get('/d/{article}-{tag}-{design_name}-{design_id}',['as' => 'web.product_design', 'uses' => 'ProductController@getProductDesign']);

I want to build this SEO friendly url: /d/mug-harry-potter-wingardium-leviosa-xfdsfsdf

And that's what I call the route into any laravel blade view:

 route('web.product_design',['article' => 'mug'), 'tag' => str_slug('Harry Potter'), 'design_name' => str_slug('Wingardium Leviosa'), 'design_id' => 'xfdsfsdf'])

The problem is that inside the ProductController I don't receive these parameters as I would like. I think Laravel confuses when it starts and when it finishes the slugs. For example, in the controller method...

# Product Design Page
    public function getProductDesign($article,$tag,$design_name,$design_id) {
      dd($article); // It gives me back 'mug', that's right.
      dd($tag); // It return me 'harry', is WRONG, I want to get 'harry-potter'.
      dd($design_name); // It return me 'potter', is WRONG, I want to get 'wingardium-leviosa'.
      dd($design_id); // It return me 'wingardium-leviosa-xfdsfsdf', is WRONG, I want to get 'xfdsfsdf'.
     }

How can I build a url SEO friendly and at the same time be able to take the parameters correctly within the controller method?



via Chebli Mohamed

How can i open excel file in browser using laravel

i have page where user can upload attachment in excel file. now he want to see that attachment, when he click on view button at that time attach file open in new tab of browser.



via Chebli Mohamed

try to get response json ,Laravel Pagination has missing meta and links with API resource

Trying

$questions=TheQuestion::paginate(5);
return $this->successResponce(TheQuestionResource::collection($questions),'','');

{ success: true,data: [{},{},{},{},{}],tag: "",message: ""}

public function successResponce($data,$tag,$message)
{
      return response()->json([
            'success' => true,
            'data' => $data,
            'tag'=>$tag,
            'message' => $message,
        ]);
}

API Resource is working fine but pagination data like current_page,total... is not showing. But When returning without JSON Response all things are coming

$questions=TheQuestion::paginate(5);
return TheQuestionResource::collection($questions);
{
    data: [],
    links: {
        first: "http://localhost:8000/api/v1/admin/question/management/show/%7B%7D?page=1",
        last: "http://localhost:8000/api/v1/admin/question/management/show/%7B%7D?page=3",
        prev: null,
        next: "http://localhost:8000/api/v1/admin/question/management/show/%7B%7D?page=2"
},
    meta: {
        current_page: 1,
        from: 1,
        last_page: 3,
        path: "http://localhost:8000/api/v1/admin/question/management/show/%7B%7D",
        per_page: 5,
        to: 5,
        total: 11
    }
}


via Chebli Mohamed

Laravel - ErrorException : Array to string conversion

I have a problem in this code in Laravel when using php artisan route:list

    ErrorException  : Array to string conversion

  at /var/www/html/app/Http/Controllers/Merchant/CountryAreaController.php:312
    308|             }
    309|         }
    310|         if (!empty($request->rental_service)) {
    311|             $service[] = 2;
  > 312|             foreach ($request->get('rental_vehicle_type' . []) as $item) {
    313|                 $area->VehicleType()->attach($item, ['service_type_id' => 2]);
    314|             }
    315|             $area->Package()->attach($request->rental_service, ['service_type_id' => 2]);
    316|         }


via Chebli Mohamed

Localization is not working for all URL in Laravel

Localization is not working for some URL in my Laravel project.

Here are some routes

route A : Route::get('/doctor', 'homeController@doctor');

route B : Route::get('/doctor/{data}', 'homeController@doctor_detail');

localization url :

Route::get('locale/{locale}',function ($locale){

    Session::put('locale',$locale);

    return redirect()->back();

});

Custom Error Route:

 Route::any('{catchall}', function() {

  return App::call('App\Http\Controllers\errorController@error');

})->where('catchall', '.*');

Localization works for route A but gives an error for route B.

Can't find any solution yet.

Anybody help, please? Thanks in advance.

If anything needs regarding the issue please tell me, I will provide.



via Chebli Mohamed