lundi 8 novembre 2021

Laraval storage:link command failing because of Database Error

When I am executing the below command in Laraval

php artisan storage:link

It throws a database connection error

 Illuminate\Database\QueryException  : SQLSTATE[HY000] [2002] Connection refused (SQL: select * from `settings`)
 at /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:669

I don't see any relation between storage:link command and database connection. Just want to understand what exactly can be wrong here.



via Chebli Mohamed

How can I fix this error related to to controller?

I have a problem, thank you for your help. I want this to be done in the Store method when a person submits a question But it gives me an error that says: thread_id required ???!

  Subscribe::query()->create([
        'thread_id'=>$thread->id,
        'user_id' => auth()->user()->id
    ]);

This is the code for my Store method, which includes the subscribe model:

 public function store(Request $request,Thread $thread)
{
    $request->validate([
        'title' => ['required', 'min:3'],
        'description' => ['required'],
        'channel_id' => ['required'],
        'thread_id' => ['required']
    ]);

    Thread::create([
        'title' => $request->title,
        'description' => $request->description,
        'user_id' => auth()->user()->id,
        'channel_id' => $request->channel_id,
    ]);

    Subscribe::query()->create([
        'thread_id' => $thread->id,
        'user_id' => auth()->user()->id
    ]);
    return redirect('/');
}

This is also the code related to View

<form action="" method="post">
@csrf
<input type="hidden" name="thread_id" value="">

<div class=" container-fluid w-75 border border-secondary rounded shadow">
    <div style="font-weight: bolder; font-size: large;" class=" my-3">فرم ارسال پرسش</div>
    <div class="input-group mb-3">
        <div class="input-group-prepend">

        </div>
        <input type="text" name="title" class="form-control" placeholder="موضوع" aria-label="Username" value=""
               aria-describedby="basic-addon1">
    </div>
    
    <div class="input-group">
        <textarea name="description" class="form-control" aria-label="With textarea" placeholder="متن پرسش"
                  style="height: 200px;"></textarea>
    </div>


    <div class="input-group mt-3 " style="direction: ltr;">
        <select name="channel_id" class="custom-select" id="channel_id" >
            <option selected disabled value="">انتخاب عنوان</option>
            @foreach(\App\Models\Channel::all() as $channel)
                <option value=""></option>
            @endforeach
        </select>

    </div>

    <div class="my-3" style="width: 100px;">
        <button class="btn btn-success" type="submit">ارسال</button>
    </div>


</div>

the problem about this code on view

<input type="hidden" name="thread_id" value="">

also i sent the Thread model on view

 public function create(Thread $thread)
{
    return view('answer-question.thread.thread-create',compact('thread'));
}

this is subcribe database enter image description here



via Chebli Mohamed

dimanche 7 novembre 2021

Cors issue in Laravel and angular application

I have hosted laravel and angular application on two different sub domain

but now getting this error :

Access to XMLHttpRequest at 'https://ift.tt/3wvKosX' from origin 'https://ift.tt/3BSZXfr' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.

CORS Middleware:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CORS
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);
$response->header('Access-Control-Allow-Origin', '*')->header('Access-Control-Allow-Headers', 'Content-type, X-Auth-Token, Authorization, Origin');

return $response;
    }
}

api.php

Route::group(['middleware' => ['api','cors'],'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']);    
});

Kernel.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        //'guest' => \App\Http\Middleware\CORS::class,
        'cors' => \App\Http\Middleware\CORS::class,
    ];
}

config/cors.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['api/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => false,

];

Any suggestion to resolve this issue. Thanks



via Chebli Mohamed

Access to XMLHttpRequest at 'https://......login' from origin 'https://.....r.in' has been blocked by CORS policy

I have hosted laravel and angular application on server it was working before but now it is throwing below error :

Access to XMLHttpRequest at 'https://......login' from origin 'https://.....r.in' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I have created CORS middleware :

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CORS
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        header('Acess-Control-Allow-Origin: *');
        header('Acess-Control-Allow-Origin: Content-type, X-Auth-Token, Authorization, Origin');
        return $next($request);
    }
}

api route file:

Route::group(['middleware' => 'api','cors','prefix' => 'auth'], function ($router) {
    Route::post('/login', [AuthController::class, 'login']);
    Route::post('/register', [AuthController::class, 'register']);
    Route::post('/logout', [AuthController::class, 'logout']);
    Route::get('/user-profile', [AuthController::class, 'userProfile']);    
});

Any solution is highly appreciated, Thanks



via Chebli Mohamed

samedi 6 novembre 2021

MPDF in Laravel can't output (inline) pdf

I am doing below code in Laravel 5.5 with mpdf 8.0

$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML('Hello World');
$mpdf->Output("test","I");

It outputs gibberish/garbage values, seemingly showing pdf file in raw form.

Some findings

  • If I use $mpdf->Output($reportPath, 'F'); (saving it to file) and the opening that. It opens the file as expected.
  • If I place die(); after $mpdf->Output("test","I"); it shows the document.
  • My suspicion is, it has something something to do with Content-type:application/pdf not being set by default but I have also tried using header("Content-type:application/pdf"); before Output but of no use. it is still showing Content-Type: text/html; charset=UTF-8 in response header in Network tab of chrome (also tried Firefox).

Some back-story

  • It used to work on php7.3 just fine, but I have to update it to php7.4 due to some library and multiple application on a single server scenario.
  • Also start using a sub-domain for my application instead of placing the directories after the domain.

I'm looking for

  • A solution that doesn't require me to place die; at the end of output.
  • Or some clue in on why this has started happening or/and perhaps why I need to place die; after Output.
  • Any other solution.

The goal is to provide some ref. for people encountering same issues in future, since I have spent hours and haven't anything that specifically address such issue.



via Chebli Mohamed

jeudi 4 novembre 2021

I have a this error en laravel : Syntax error or access violation: 1075 Incorrect table definition.How do I solve this problem?

** SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table definition; there can be only one auto column and it must be defined as a key (SQL: create table loans (id_loan int unsigned not null auto_increment primary key, book_id bigint unsigned not null auto_increment primary key, user_id bigint unsigned not null auto_increment primary key, date_vto date not null) default character set utf8mb4 collate 'utf8mb4_unicode_ci').How do I solve this problem?

**

Migrations

public function up()
{
    Schema::create('books', function (Blueprint $table) {
        $table->increments('id_book');
        $table->string('title');
        $table->integer('amount');
    });
}
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('username');
        $table->string('password');
        $table->string('role');

    });
}
 public function up()
{
    Schema::create('loans', function (Blueprint $table) {
        $table->increments('id_loan');
        $table->bigIncrements('book_id')->unsigned();
        $table->bigIncrements('user_id')->unsigned();
        $table->date('date_vto');

        $table->foreign('book_id')->references('id_book')->on('books')->onDelete('cascade');
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

Models books

public function loans(){
    return $this->hasMany(Loans::class);
}

Models Loans

public function books()
{
    return $this->belongsTo(Books::class, 'book_id', 'id_book');
}
public function users()
{
    return $this->belongsTo(Users::class, 'user_id', 'id');
}

Models Users

public function loans(){
        return $this->hasMany(Loans::class);
    }


via Chebli Mohamed

query in eloquent model

I´m traying to do this query in eloquent.

SELECT llamada_estado.desc, count(id_estado) 
                                      FROM estadisticas INNER JOIN llamada_estado ON estadisticas.id_estado = llamada_estado.id 
                                      WHERE updated_at BETWEEN '2021-11-01' AND '2021-11-30' 
                                      GROUP BY estadisticas.id_estado

i´m traying this:

$query2=Estadisticas::query()->whereDate('updated_at', '<=', $toDate)
                                     ->whereDate('updated_at', '>=', $fromDate)
                                     ->join('llamada_estado', 'estadisticas.id_estado', '=', 'llamada_estado.id')
                                     ->groupBy('estadisticas.id_estado')
                                     ->get();

but always return that x column it´s not included in group by, but in phpMyAdmin i´m doing this query:

SELECT llamada_estado.desc, count(id_estado) 
FROM estadisticas 
INNER JOIN llamada_estado ON estadisticas.id_estado = llamada_estado.id 
WHERE updated_at BETWEEN '2021-11-01' AND '2021-11-30' 
GROUP BY estadisticas.id_estado

and this it´s my result:

desc, count(id_estado)
NUEVA 399
PENDIENTE 104
ANULADA 117
CONFIRMADA 50
PASADA A COMERCIALES 175
MAYOR 196
ERRONEO NO EXISTE 649
AUSENTE 681

and i need this result in eloquent.

my tables it´s:

my table call status

CREATE TABLE `llamada_estado` (
  `id` int(10) UNSIGNED NOT NULL,
  `nombre` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
  `desc` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
  `clase_span` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `clase` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `hex` varchar(7) COLLATE utf8mb4_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Volcado de datos para la tabla `llamada_estado`
--

INSERT INTO `llamada_estado` (`id`, `nombre`, `desc`, `clase_span`, `clase`, `hex`) VALUES
(1, 'nueva', 'NUEVA', 'badge bg-primary text-white', 'primary', '#5c80d1'),
(2, 'pendiente', 'PENDIENTE', 'badge bg-warning text-white', 'warning', '#f3b760'),
(3, 'anulada', 'ANULADA', 'badge bg-danger text-white', 'danger', '#d26a5c'),
(4, 'confirmada', 'CONFIRMADA', 'badge bg-success text-white', 'success', '#46c37b'),
(5, 'comercializada', 'PASADA A COMERCIALES', 'badge bg-info text-white', 'info', '#70b9eb'),
(6, 'confirmada-ausente', 'CONFIRMADA/AUSENTE', 'badge bg-secondary text-white', 'secondary', '#6c757d'),
(7, 'confirmada-anulada', 'CONFIRMADA/ANULADA', 'badge bg-dark text-white', 'dark', '#343a40'),
(8, 'MAYOR', 'MAYOR', 'badge bg-danger text-white', 'danger', '#d26a5c'),
(9, 'Erroneo-no existe', 'ERRONEO NO EXISTE', 'badge bg-danger text-white', 'danger', '#d26a5c'),
(10, 'Robinson', 'ROBINSON', 'badge bg-danger text-white', 'danger', '#d26a5c'),
(11, 'ausente', 'AUSENTE', 'badge bg-warning text-white', 'warning', '#f3b760');

my table statistics

--
-- Estructura de tabla para la tabla `estadisticas`
--

CREATE TABLE `estadisticas` (
  `id` int(10) UNSIGNED NOT NULL,
  `id_empleado` int(10) UNSIGNED NOT NULL,
  `id_llamada` int(10) UNSIGNED NOT NULL,
  `id_estado` int(10) UNSIGNED NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Volcado de datos para la tabla `estadisticas`
--

INSERT INTO `estadisticas` (`id`, `id_empleado`, `id_llamada`, `id_estado`, `created_at`, `updated_at`) VALUES
(72, 9, 89008, 1, '2021-08-26 06:47:38', '2021-08-26 06:47:38'),
(75, 9, 56617, 1, '2021-08-26 06:47:38', '2021-08-26 06:47:38'),
(77, 9, 78359, 1, '2021-08-26 06:47:38', '2021-08-26 06:47:38'),
(80, 9, 70361, 1, '2021-08-26 06:47:39', '2021-08-26 06:47:39'),
(87, 9, 89023, 1, '2021-08-26 06:47:39', '2021-08-26 06:47:39'),
(89, 9, 84052, 1, '2021-08-26 06:47:39', '2021-08-26 06:47:39'),
(90, 9, 89026, 1, '2021-08-26 06:47:39', '2021-08-26 06:47:39'),
(92, 9, 89028, 1, '2021-08-26 06:47:39', '2021-08-26 06:47:39'),
(108, 23, 89044, 1, '2021-08-26 06:50:12', '2021-08-26 06:50:12'),
(109, 23, 89045, 1, '2021-08-26 06:50:12', '2021-08-26 06:50:12'),
(112, 23, 89048, 1, '2021-08-26 06:50:12', '2021-08-26 06:50:12'),
(124, 23, 56496, 1, '2021-08-26 06:50:12', '2021-08-26 06:50:12'),
(126, 23, 89062, 1, '2021-08-26 06:50:12', '2021-08-26 06:50:12'),
(129, 23, 89065, 1, '2021-08-26 06:50:13', '2021-08-26 06:50:13'),
(130, 23, 89066, 1, '2021-08-26 06:50:13', '2021-08-26 06:50:13'),
(142, 24, 89078, 1, '2021-08-26 06:50:36', '2021-08-26 06:50:36'),
(144, 24, 55175, 1, '2021-08-26 06:50:36', '2021-08-26 06:50:36'),
(146, 24, 58093, 1, '2021-08-26 06:50:36', '2021-08-26 06:50:36'),
(149, 24, 72171, 1, '2021-08-26 06:50:36', '2021-08-26 06:50:36'),
(152, 24, 89088, 1, '2021-08-26 06:50:36', '2021-08-26 06:50:36'),
(155, 24, 89091, 1, '2021-08-26 06:50:36', '2021-08-26 06:50:36'),
(156, 24, 89092, 1, '2021-08-26 06:50:36', '2021-08-26 06:50:36'),
(161, 24, 73468, 1, '2021-08-26 06:50:36', '2021-08-26 06:50:36'),
(164, 24, 89100, 1, '2021-08-26 06:50:36', '2021-08-26 06:50:36'),
(165, 24, 89101, 1, '2021-08-26 06:50:36', '2021-08-26 06:50:36'),
(193, 26, 56101, 1, '2021-08-26 06:51:36', '2021-08-26 06:51:36'),
(195, 26, 89131, 1, '2021-08-26 06:51:36', '2021-08-26 06:51:36'),
(196, 26, 83856, 1, '2021-08-26 06:51:36', '2021-08-26 06:51:36'),
(197, 26, 78782, 1, '2021-08-26 06:51:36', '2021-08-26 06:51:36'),
(225, 11, 89161, 1, '2021-08-26 06:52:01', '2021-08-26 06:52:01'),
(227, 11, 89163, 1, '2021-08-26 06:52:01', '2021-08-26 06:52:01'),
(229, 11, 89165, 1, '2021-08-26 06:52:01', '2021-08-26 06:52:01'),
(231, 11, 85394, 1, '2021-08-26 06:52:01', '2021-08-26 06:52:01'),
(233, 11, 89169, 1, '2021-08-26 06:52:01', '2021-08-26 06:52:01'),
(236, 11, 60645, 1, '2021-08-26 06:52:01', '2021-08-26 06:52:01'),
(242, 11, 84919, 1, '2021-08-26 06:52:01', '2021-08-26 06:52:01'),
(246, 11, 59005, 1, '2021-08-26 06:52:01', '2021-08-26 06:52:01'),
(263, 11, 68628, 1, '2021-08-26 06:52:37', '2021-08-26 06:52:37'),
(264, 11, 89200, 1, '2021-08-26 06:52:37', '2021-08-26 06:52:37'),
(265, 11, 89201, 1, '2021-08-26 06:52:37', '2021-08-26 06:52:37'),
(268, 11, 89204, 1, '2021-08-26 06:52:37', '2021-08-26 06:52:37'),
(269, 11, 89205, 1, '2021-08-26 06:52:37', '2021-08-26 06:52:37'),

My question is, how i can to do this query in eloquent?

Thanks for help and read



via Chebli Mohamed