php – Laravel Request validation exists e nullable ao mesmo tempo

Criei uma classe request e injeto ela no método store da controler. Meu método rules dentro da classe tem a seguinte chave:

public function rules()
{
    return (
    //...
    'campo_id' => 'sometimes|nullable|exists:tabela,pk',
    //...
    );
}

quando o valor é null e entra nessa validação, ele cai na validação exists e me retorna a mensagem correspondente. Minha intenção é deixar null mesmo. Alguma sugestão?

problema al usar join en laravel

Colegas tengo la siguiente consulta:

$count_tareas = DB::table('personas')
                    ->join('soluciones', 'soluciones.user_id', '=', 'personas.id')
                    ->join('participantes', 'participantes.persona_id', '=', 'personas.id')
                    ->where('soluciones.user_id', '=', $this->id)
                    ->orwhere('participantes.persona_id', '=', $this->id)
                    ->select('soluciones.*', 'participantes.*')
                    ->get();

Estoy realizando un join con dos tablas para saber si una persona se encuentra en la tabla soluciones y en la tabla participantes para así obtener la cantidad de veces que esa persona aparece tanto en soluciones como en participantes. Después lo intento muestro en pantalla de la siguiente forma: return count($count_tareas) pero me el resultado es cero. En la base de datos revise y si aparece el usuario.

donde puede estar el problema colegas. sldos

http – Como setar utf-8 em um csv que retorna uma collection do Laravel?

Problema:
Quando baixo o arquivo csv ele me retorna com os caracteres bugados, dessa maneira:
inserir a descrição da imagem aqui

porém, já setei o "Content-type" => "text/csv; charset=utf-8", e mesmo assim não surtiu efeito.

O código que gera o csv é este:

public function csv() {
        if(Gate::denies('is-admin')) {
            return redirect()->back()->with('error', __('You are not allowed to do this'));
        }

        $drafts = Draft::select('id',
        'nome',
        'conjuge_nome')->get()->toArray();



        foreach($drafts as $key => $draft) {
            $drafts($key)('cod_ibge') = '';
            foreach($draft as $keyValue => $value) {
                if($value === null) {
                    $drafts($key)($keyValue) = '';
                }
            }

            unset($drafts($key)('content'));
            unset($drafts($key)('user_id'));
            unset($drafts($key)('file_cpf'));
            unset($drafts($key)('file_rg_cnh'));
            unset($drafts($key)('file_comprovante_residencia'));
            unset($drafts($key)('file_serasa'));
        }

        $columns = ('Id no Emissor',
        'Nome do mutuário principal (ou Razão Social se empresa)',
        'Nome do mutuário secundário');

        $headers = array(
            "Content-type" => "text/csv; charset=utf-8",
            "Content-Disposition" => "attachment; filename=contratos.csv",
            "Pragma" => "no-cache",
            "Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
            "Expires" => "0"
        );

        $callback = function() use ($drafts, $columns)
        {
            $file = fopen('php://output', 'w');
            fputcsv($file, $columns);

            foreach($drafts as $draft) {
                fputcsv($file, $draft);
            }
            fclose($file);
        };
        return response()->stream($callback, 200, $headers);
    }

Observação: Diminui a quantidade de campos q o SQL e o array q crio traz para o código não ficar tão grande sem necessidade.

multi tenancy – Trocar o valor APP_URL do Laravel conforme o domínio que estiver acessando o site

Caros, estou escrevendo uma aplicação que poderá ser acessada por vários domínios e claro que preciso trocar a constante do .env APP_URL para que a formatação dos endereços de imagens por exemplo ocorram no domínio de acesso.

Já busquei esta informação por todos os cantos e não encontro uma explicação clara.

Já sei como implementar rotas diferentes por domínio, mas, como trocar o domínio da aplicação, não descobri de jeito nenhum.

Agradeço a ajuda!

laravel – Call to a member function getRelationExistenceQuery() on null

el error se produce al intentar ejecutar los seeds.

este es el error detallado:

 at vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php:49
45|         $method = $this->canUseExistsForExistenceCheck($operator, $count)
46|                         ? 'getRelationExistenceQuery'
47|                         : 'getRelationExistenceCountQuery';
48|

49| $hasQuery = $relation->{$method}(
50| $relation->getRelated()->newQueryWithoutRelationships(), $this
51| );
52|
53| // Next we will call any given callback as an “anonymous” scope so they can get the

  +3 vendor frames

4 database/factories/UserFactory.php:59
IlluminateDatabaseEloquentModel::__callStatic()

  +6 vendor frames

11 (internal):0
IlluminateDatabaseEloquentFactoryBuilder::IlluminateDatabaseEloquent{closure}()

esta es la factory:

use AppUser;
use AppCategory;
use AppProduct;
use AppTransaction;
use AppSeller;
use FakerGenerator as Faker;
use IlluminateSupportStr;

$factory->define(User::class, function (Faker $faker) {
    static $password;
    return (
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => $password ?: $password = bcrypt('secret'),
        'remember_token' => Str::random(10),
        'verified' => $verificado = $faker->randomElement((User::USUARIO_VERIFICADO, User::USUARIO_NO_VERIFICADO)),
        'verification_token'=> $verificado == User::USUARIO_VERIFICADO ? null : User::generarVerificationToken(),
        'admin' => $faker->randomElement((User::USUARIO_ADMINISTRADOR, User::USUARIO_REGULAR)),
    );
});

$factory->define(Category::class, function (Faker $faker) {
    return (
        'name' => $faker->word,
        'description'=> $faker->paragraph(1),
    );
});

$factory->define(Product::class, function (Faker $faker) {
    return (
        'name' => $faker->name,
        'description'=> $faker->paragraph(1),
        'quantity'=> $faker->numberBetween(1, 10),
        'status'=> $faker->randomElement((Product::PRODUCTO_DISPONIBLE, Product::PRODUCTO_NO_DISPONIBLE)),
        'image'=> $faker->randomElement(('1.jgp', '2.jgp', '3.jgp')),
        'seller_id'=> User::all()->random()->id,
    );
});


$factory->define(Transaction::class, function (Faker $faker) {
    
    $vendedores= Seller::has('products')->get()->random();
    $comprador= User::all()->except($vendedores->id)->random();
    return (
        'quantity'=> $faker->numberBetween(1, 3),
        'buyer_id'=> $comprador->id,
        'product_id'=> $vendedores->products->random()->id,
    );
});

este es el seed:

use IlluminateDatabaseSeeder;
use AppUser;
use AppCategory;
use AppProduct;
use AppTransaction;

public function run()
    {
        DB::statement('SET FOREIGN_KEY_CHECKS = 0');
        User::truncate();
        Product::truncate();
        Category::truncate();
        Transaction::truncate();
        DB::table('category_product')->truncate();

        $cantidadusuarios= 200;
        $cantidadcategorias= 30;
        $cantidadproductos= 1000;
        $cantidadtransacciones= 1000;

        factory(User:: class, $cantidadusuarios)->create();
        factory(Category:: class, $cantidadcategorias)->create();
        factory(Product:: class, $cantidadtransacciones)->create()->each(
            function($producto)
            {
                $categorias= Category::all()->random(mt_rand(1, 5))->pluck('id');
                $producto->categories()->attach($categorias->first());
            }
        );
        factory(Transaction:: class, $cantidadtransacciones)->create();

    }

Laravel- DB Query Duplicates record twice

I am using Laravel-5.8 for this Query:

    $published_goalss = DB::table('hr_employees AS e')
                ->join('hr_employees AS em','em.employee_code','=','e.line_manager_id')
                ->join('hr_departments AS d','e.department_id','=','d.id')
                ->join('hr_employees AS eh','eh.employee_code','=','d.dept_head')
                ->join('hr_employees AS eb','eb.employee_code','=','d.hr_business_partner_id')
                ->join('appraisal_goals AS ag','ag.company_id','=','e.company_id')
                 ->select(
                    'e.employee_code as staff_id',
                    DB::raw('CONCAT(e.first_name, " ", e.last_name) AS full_name'),
                    DB::raw('IF(e.gender_code = 0, "Female", "Male") AS gender'),
                    'e.email as official_email',
                    DB::raw('CONCAT(eh.first_name, " ", eh.last_name) AS hod_name'),
                    DB::raw('CONCAT(eb.first_name, " ", eb.last_name) AS hrbp_name'),
                    DB::raw('(CASE WHEN ag.is_approved = 3 THEN "Approved" WHEN ag.is_approved = 2 THEN "Not Approved" WHEN ag.is_approved = 1 THEN "Awaiting Approval" ELSE "Draft" END) AS goal_status')
             )
                ->whereIn('e.employee_code', $publishedgoals)
                ->where('e.company_id', $userCompany)
                ->where('e.hr_status', 0) 
            ->distinct()
            ->get();

Initially it duplicates 4 times, but when I added

 ->distinct()  ->get();

it reduces the duplication to just two.

I dealyy the query should give me 2 records, but it is giving me 4 records.

How do I resolve this.

Thanks

Laravel ao carregar um relacionamento não aparece ao retornar como json

Ao tentar carregar as imagens de um produto não são inclusas ao retornar

Modelo:

class Product extends Model
{
    public function images()
    {
        return $this->hasMany(ProductImage::class);
    }
}

Controller:

class HomeController extends Controller
{
    public function getProducts()
    {
        $products = Product::with('images')->find(1);    
        return response()->json( $products, 200);
    }
}

Resultado:

{
  "id": 1,
  "name": "Tenis Adidas Flow Limited Edition",
  "price": 549.99,
  "stock": 0,
  "active": 0,
  "created_at": "17-06-20",
  "updated_at": "20-06-20"
}

Se eu fizer um $products->images no retorno funciona e fica assim:

(
  {
    "id": 5,
    "path": "products/1/SR84EetnuQW7WDetQBAurHypJPwrOiddyXWFDkAh.jpeg",
    "product_id": 1
  },
  {
    "id": 12,
    "path": "products/1/7cIkR4i0F3zY6fsKibqvKQIxtSEusCZmrmxx75nk.jpeg",
    "product_id": 1
  }
)

então creio que a relação está funcionando corretamente, porem não consigo entender o motivo de não ir no retorno.

Laravel 7: "Trying to get property of non-object" ¿Cómo resuelvo esto?

Ya he estado buscando en otros hilos de este mismo foro y por internet en general y no encuentro una solución para mi situación en concreto.

Lo que sucede es que a la mínima que añado un dato nuevo a mi base de datos a través de mis crud, salta este error cuando intento acceder de nuevo a mi página principal de home (home.blade.php). Home sí va bien antes de lo de añadir algo nuevo, pero después de esto salta este error y no sé qué tengo que hacer.

Añado capturas (marcando en rojo los sitios a los que se puede acceder para interactuar con mis crud) y el código de mi home.blade.php porque me supongo que es ahí donde está el kit del problema, ya que mis crud en sí sí van bien.

<head>
    <title>Adrián Pérez: Home</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body class="bg-secondary">
    <header class="w-100 bg-dark">
        <div class="d-flex">
            <a href="/" class="text-decoration-none"><img src="{{asset('img/logo1.jpg')}}" alt="" width="75" height="75"></img></a>
            <a href="/" class="text-decoration-none text-white"><h1>Aula Campus</h1></a>
        </div>
    </header>
    </br>
    <div class="d-flex">
        <aside class="bg-dark w-25">
            <nav>
                <ul class="list-unstyled">
                    <li><a href="/roles" class="font-weight-bold text-white text-decoration-none"><h4>Roles</h4></a></li>
                    <li><a href="/users" class="font-weight-bold text-white text-decoration-none"><h4>Usuarios</h4></a></li>
                    <li><a href="/posts" class="font-weight-bold text-white text-decoration-none"><h4>Posts</h4></a></li>
                    <li><a href="/comments" class="font-weight-bold text-white text-decoration-none"><h4>Comentarios</h4></a></li>
                    <li><a href="/attachments" class="font-weight-bold text-white text-decoration-none"><h4>Adjuntos</h4></a></li>
                </ul>
            </nav>
        </aside>
        <main class="bg-light w-75">
            </br>
            <div class="bg-white d-block mx-auto w-75">
                <a href="/posts" class="text-center w-100 btn btn-outline-primary">Publicar</a>
            </div>
            </br>
            @foreach($posts as $post)
                <div class="w-75 mx-auto d-block bg-white">
                    <div class="d-flex">
                        <img src="{{asset('img/userIcon.png')}}" alt="" width="35" height="35"></img>
                        <p class="font-weight-bold">{{$post->user->first_name}} {{$post->user->last_name}}</p>
                    </div>
                    <p>{{$post->updated_at}}</p>
                    <h3 class="text-center">{{$post->title}}</h3>
                    </br>
                    <div class="border-bottom">
                        <img src="{{asset('img/dinantia.jpg')}}" alt="" class="d-block mx-auto border"></img>
                        </br>
                        <p class="text-justify d-block mx-auto">{{$post->text}}</p>
                    </div>
                    </br>
                    <div>
                        <div class="float-left">
                            <a href="#" class="text-decoration-none text-danger">
                                <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-heart-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
                                    <path fill-rule="evenodd" d="M8 1.314C12.438-3.248 23.534 4.735 8 15-7.534 4.736 3.562-3.248 8 1.314z"/>
                                </svg>
                            </a>
                        </div>
                        <p class="float-right">{{count($comments)}} Comentarios</p>
                    </div>
                    </br>
                    </br>
                    @foreach($comments as $comment)
                        <div class="d-flex">
                            <img src="{{asset('img/userIcon.png')}}" alt="" width="35" height="35"></img>
                            <div class="bg-light w-75">
                                <p class="font-weight-bold">{{$comment->user->first_name}} {{$comment->user->last_name}}</p>
                                <p>{{$comment->text}}</p>
                            </div>
                        </div>
                        </br>
                    @endforeach
                    <div class="d-flex">
                        <form method="post" action="{{route('comments.store')}}">
                            @csrf
                            <label for="text"></label>
                            <input type="text" name="text"/>
                            <button type="submit" class="btn btn-danger">Enviar</button>
                        </form>
                    </div>
                </div>
                </br>
            @endforeach
        </main>
    </div>
    </br>
    <footer class="bg-primary w-100">
        <div class="text-center text-white">
            <p>Adrián Pérez</p>
            <p>11 de julio de 2020</p>
        </div>
    </footer>
</body>

introducir la descripción de la imagen aquí

introducir la descripción de la imagen aquí

how get dynamic parameter and pass data to controllers in laravel

i have a group route in laravel that get a parameter like below :

Route::group(('prefix' => '{ProjectCode}'),function(){
 Route::get('/categories', 'CategoriesController@Categories');
 Route::get('/add-category', 'CategoriesController@AddCategory');
});

The ProjectCode is an id, that needs to get some data from the database
I want to pass the got data to controllers that they are in sub of the route group
and avoid getting data in every function in controller

php – Laravel parent/child relationships

I have the following db table that has a corresponding model inside my laravel app.

CREATE TABLE Comments (
  handle           varchar(255) NOT NULL,
  parent_handle    varchar(255) DEFAULT NULL,
  comment_topic    varchar(255) NOT NULL,
  user_id          bigint(20)   NOT NULL,
  comment_body     longtext     NOT NULL,
  depth            int(11)      NOT NULL DEFAULT 1,
  created_at       timestamp    NULL DEFAULT NULL,
  updated_at       timestamp    NULL DEFAULT NULL,
  deleted_at       timestamp    NULL DEFAULT NULL,
  PRIMARY KEY (handle),
  KEY user_id_key(user_id),
  CONSTRAINT comments_user_id_fk FOREIGN KEY (user_id) REFERENCES Users(id) ON DELETE CASCADE,
) ENGINE=InnoDB;

Parent child relationships are nestable via handle-parent_handle relationships. That means:

handle   | parent_handle | user_id | comment                                 | depth
---------|---------------|---------|-----------------------------------------|-------------
handle1  | null          | 3       | this is the first comment               | 1
handle2  | handle1       | 2       | this is a reply to the first comment    | 2
handle3  | null          | 4       | this is a new top level comment         | 1
handle4  | handle2       | 3       | this is a reply to handle2              | 3
handle5  | handle4       | 4       | this is a reply to handle4              | 4
handle6  | handle2       | 1       | this is also a reply to handle2         | 3
handle7  | handle5       | 3       | this is a reply to handle5              | 5
handle8  | handle7       | 4       | reply to handle7                        | 6

I want to be able to get back a nested result. Therefore I’m using the following CTE to get back the nested relationships.

WITH RECURSIVE NestedComments AS (
    SELECT handle, comment_body, user_id, parent_handle, created_at, depth
      FROM Comments WHERE topic = 'topicid1' AND parent_handle IS NULL
    UNION ALL
    SELECT c.handle, c.comment_body, c.user_id, c.parent_handle, c.created_at, depth
      FROM Comments AS c
INNER JOIN NestedComments AS nc
        ON c.parent_handle = nc.handle
)
    SELECT NC.handle, NC.parent_handle, NC.comment_body, NC.created_at, NC.depth, U.username
      FROM NestedComments AS NC
INNER JOIN Users AS U 
        ON U.id = NC.user_id
     WHERE NC.depth <= 3
  ORDER BY NC.created_at;

My problem is that I want to transform the above to the following json result:

{
  "object": "comment",
  "handle": "handle1"
  "user": (
    "username": "jsmith",
    "display_name": "John Smith",
  ),
  "body": "this is the first comment",
  "reply_count": 5,
  "replies": ({
      "object": "comment",
      "handle": "handle2"
      "user": (
         "username": "dsmith",
         "display_name": "Dan Smith",
      ),
      "body": "this is a reply to the first comment",
      "reply_count": 2,
      "replies": ({
          "object": "comment",
          "handle": "handle4"
          "user": (
             "username": "jsmith",
             "display_name": "John Smith",
          ),
          "body": "this is a reply to handle2",
          "reply_count": 3,
          "replies": ()
         }, {
          "object": "comment",
          "handle": "handle6",
          "user": (
             "username": "JAsmith",
             "display_name": "Jacklyn Smith",
          ),
          "body": "this is also a reply to handle2",
          "reply_count": 0,
          "replies": ()
        }
      )}
   )
}, {
  "object": "comment",
  "handle": "handle3",
  "user": (
    "username": "jesmith",
    "display_name": "Jenny Smith",
  ),
  "body": "this is a new top level comment",
  "reply_count": 0,
  "replies": ()
}

I do have the Parent and Replies eloquent relationships defined

final public function Parent() : HasOne
{
    return $this->hasOne(Comments::class, 'handle', 'parent_handle');
}

final public function Replies() : HasMany
{
    return $this->hasMany(Comments::class, 'parent_handle', 'handle');
}

But I have no idea how to adjust it so that I get the json response I require.