Penaf

Penaf

Member Since 6 Months Ago

Experience Points 770
Experience
Level
Lessons Completed 0
Lessons
Completed
Best Reply Awards 0
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

12 Dec
20 hours ago

Penaf started a new conversation Query A Many To Many Relationship Table

Good afternoon,

Basically I have 2 models related with many to many. Species that might or might not be present on differents zones of different maps.

Table especies

  • id
class Especie extends Model
{
    public function zona()
    {
        return $this->belongsToMany('App\Zona', 'especie_zona', 'especie_id', 'zona_id');
    }
}

Table zonas

  • id
  • name
  • mapa_id
class Zona extends Model
{
    public function especie()
    {
        return $this->belongsToMany('App\Especie', 'especie_zona', 'zona_id', 'especie_id');
    }

}

In the middle of both tables sits a table especie_zona (with about 100k records)

  • especie_id
  • zona_id

I'm trying to get all zones where a species is present.

What I have so far ...

On the MapsController

        $zonasMarcadas = Zona::whereHas('especie', function ($query) use ($id) {
            $query->where('id', '=', $id);
        })->get();

which generates the query

select * from `zonas` where exists (select * from `especies` inner join `especie_zona` on `especies`.`id` = `especie_zona`.`especie_id` where `zonas`.`id` = `especie_zona`.`zona_id` and `id` = '3041')

that takes about 60 seconds to return results when I realy want is the query

SELECT * FROM especie_zona WHERE especie_id = 85
´´´

that takes about 0.125 seconds to return 400 results.

What am I doing wrong ? Any help greatly appreciated!
17 Oct
1 month ago

Penaf started a new conversation Undefined Builder::links() When Paginating Many To Many Relation

Good evening,

while this bit on my controller works perfect:

    public function info($coleccao_tematica) {

        $coleccaoTematica = ColeccaoTematica::where('slug', 'LIKE', $coleccao_tematica)
            ->withCount('multimedia', 'especie')
            ->with('multimedia', 'poi', 'vid', 'capa')
            ->with(['especie' => function ($query) {
                $query->paginate(2);
            }])

            ->first();

        return view('coleccao_tematica', compact('coleccaoTematica'));

    }

On my blade template doing

{{ $coleccaoTematica->especie()->links() }}

doesn't generate the pagination and gives the follwing error:

Call to undefined method Illuminate\Database\Query\Builder::links() (View: /home/vagrant/Code/ecocampus/resources/views/coleccao_tematica.blade.php)

What am I missing? :/

20 Sep
2 months ago

Penaf left a reply on Pagination Of Data From A Relation

with the loops I can access the properties ... but $galeriaInfo->links() is not generating the pagination ...

Penaf started a new conversation Pagination Of Data From A Relation

            $galeriaInfo = Galeria::where('slug', 'LIKE', $slug)
                ->with(['multimedia'])
                ->withCount('multimedia')
                ->paginate(15);

Printing this $galeriaInfo I see the correct information on the screen ... info of the specific gallery and 15 images retrived from the other model. But how can I access the info on the blade template?

Doing

<h1>Galeria<span class="verde">{{ $galeria->nome }}</span></h1>

Gives: Undefined property: Illuminate\Pagination\LengthAwarePaginator::$nome

19 Sep
2 months ago

Penaf left a reply on Using Accessor To Select One Result Of A Related Table

Like so:

    public function getCapaAttribute()
    {

        $capa = $this->multimedia()
            ->where('isCover', '=', 1)
            ->pluck('multimedia_id')
            ->first();

        if (!isset($capa)) {
            $capa = $this->multimedia()
                ->where('isCover', '=', 0)
                ->pluck('multimedia_id')
                ->first();
        }

        if (!isset($capa)) {
            $capa = 7506;
        }

   }

Have a feeling the code could be much more simpler and efficient ... but it's working.

Penaf left a reply on Using Accessor To Select One Result Of A Related Table

I think I can't use it due to this:

There are 3 possibilities:

  • No cover photo defined, no photos at all ... output must be 7506
  • No cover photo defined, photos exist ... output can be any multimedia id
  • Cover photo defined ... output is the corresponding id.

Penaf left a reply on Using Accessor To Select One Result Of A Related Table

Just some more info...

With this I'm getting 7506 all the time:

    public function getCapaAttribute()
    {
        $capa = '';

        if (!isset($this->multimedia)) {
            foreach ($this->multimedia as $k => $v) {
                $capa = $v->id;
                if ($v->isCover === 1) {
                    $capa = $v->id;
                    break;
                }
            }
        } else {
            $capa = 7506;
        }

         return $capa;
    }

What comes from the database is:

especie_id | multimedia_id | isCover
888 | 9984 | 1
888 | 9985 | 0
888 | 15154 | 0
888 | 15155 | 0
888 | 15156 | 0
888 | 15157 | 0

Penaf started a new conversation Using Accessor To Select One Result Of A Related Table

Having this:

class Especie extends Model
{

    protected $table = 'especies';


    public function multimedia()
    {
        return $this->belongsToMany('App\Multimedia', 'especie_multimedia', 'especie_id', 'multimedia_id')->withPivot('isCover');
    }

Is it possible to do somekind of accessor that gives me the multimedia_id from the pivotal table where isCover = 1 ? Or is there a bettter/faster way to do this?


    protected $appends = ['nome_total'];

    public function getCoverAttribute()
    {

    return $multimedia_id;

    }

Penaf left a reply on Acessor On The Model To Get A Full_name

LOL! Thanks friends, I'm gonna throw myself of a bridge now! :D

About the == I waw it on another question, thought it was strange but went for it anyway! :)

Penaf left a reply on Indirect Modification Of Overloaded Property App\...

Thanks @lostdreamer_nl ! I did that too but thought it was kind of "hacky"

Penaf started a new conversation Acessor On The Model To Get A Full_name

I'm trying to get the full name of a species that is composed of the name, first word of subSpecie, first word of variety and first word of form.

I think I have to create an accessor. The attribute is showing in the output but it's empty. Here's what I have so far:

class Especie extends Model
{

    protected $table = 'especies';

    protected $guarded = ['id'];

    protected $appends = ['nome_total'];



    public function getNomeTotalAttribute()
    {

        $nome = $this->attributes['nome'];

        if (!empty($this->attributes['subEspecie'])) {
            $nome .= ' subesp. ' . explode(' ', trim($this->attributes['subEspecie']))[0];
        }

        if (!empty($this->attributes['variedade'])) {
            $nome .= ' var. ' . explode(' ', trim($this->attributes['variedade']))[0];
        }

        if (!empty($this->attributes['forma'])) {
            $nome .= ' for. ' . explode(' ', trim($this->attributes['forma']))[0];
        }

        return $this->attributes['nome_total'] == $nome;

    }

Where am I failing?

Penaf started a new conversation Indirect Modification Of Overloaded Property App\...

i'm not really sure what I'm doing wrong here...

´´´ $infoEspecie = Especie::where('id', '=', $id)->first(); $res = TipoDistribuicao::all();

        $infoEspecie->dist = array();

        foreach ($res as $k => $v) {

            $infoEspecie->dist[$v->nomeVector] = array(
                'id' => $v->id,
                'nome' => $v->nome,
                'nomeCurto' => $v->nomeCurto,
                'zonas' => array(),
                'zonasMarcadas' => array(),
                'html' => ''
            );
}

´´´

On a non-laravel code was working fine and now i'm refactoring the code to use eloquent and i'm getting this error. Read somewhere else this is happening because of magic methods ... i'm lost.

12 Sep
3 months ago

Penaf started a new conversation Strange Results Using Find() And Where()

Evening all, This might be a noob question, if so my appologies.

When passing to this function $id = 3

   public function editar($id)
    {
        $documento = Documento::find($id)->with(['autor'])->first();
    return $document;
    }

shows me the document with id = 1 and this

   public function editar($id)
    {
        $documento = Documento::where('id', $id)->with(['autor'])->first();
    return $document;
    }

shows me the correct document with the id = 3

Thanks for your time!

10 Sep
3 months ago

Penaf left a reply on Searching Field From Relation Table

@staudenmeir, @Cronix and @Snapey ... that was a great team effort and every one of you made a key contribution to my problem! Thanks so much all:

Working code is:

$search = $request->input('search.value');

            $familias = Familia::where('nome', 'LIKE', '%' . $search . '%')
                ->offset($start)
                ->limit($limit)
                ->with(['ordem.sub_classe.classe.sub_divisao.divisao'])
                ->withCount('especie')
                ->orWhereHas('ordem', function($q) use ($search){
                    $q->where('nome', 'LIKE', '%' . $search . '%');
                })
                ->orderBy($order, $dir)
                ->get();

            $totalFiltered = Familia::where('nome', 'LIKE', "%{$search}%")
                ->orWhereHas('ordem', function($q) use ($search){
                    $q->where('nome', 'LIKE', '%' . $search . '%');
                })
                ->count();

Now I'll go on to add search parameters for the other fields, sub_classe, classe, etc! :)

Penaf left a reply on Searching Field From Relation Table

Yup .... on $familias and on $totalFiltered

Penaf left a reply on Searching Field From Relation Table

Oh good Lord .... missed that! Thanks @staudenmeir

The thing is, now this doesn't return results at all when I perform searches I already know the results either for the nome field on the familias table or for the nome field on the ordens tables.

Another step closer! Yay

Penaf started a new conversation Searching Field From Relation Table

Trying to search a column from a related table. I'm not getting good results but I feel I'm not that far. For what I read here and on Stackoverflow I know whereHas is the way to go but I'm missing something here. Any help? Thanks in advance

Here are my models

class Familia extends Model
{

    // Irrelevant code ommited

    public function ordem()
    {
        return $this->belongsTo('App\Ordem');
    }

    public function especie()
    {
        return $this->hasMany('App\Especie');
    }

}
class Ordem extends Model
{

    // Irrelevant code ommited

    public function familia()
    {
        return $this->hasOne('App\Familia');
    }

    public function sub_classe()
    {
        return $this->belongsTo('App\SubClasse');
    }

}

Tables

familias 
- id
- nome 
- ordem_id

ordens
- id
- nome
- sub_classe_id

And On FamiliaController I managed to get this far:

            $search = $request->input('search.value');

            $familias = Familia::where('nome', 'LIKE', '%' . $search . '%')
                ->offset($start)
                ->limit($limit)
                ->with(['ordem', 'ordem.sub_classe', 'ordem.sub_classe.classe', 'ordem.sub_classe.classe.sub_divisao', 'ordem.sub_classe.classe.sub_divisao.divisao'])
                ->withCount('especie')
                ->whereHas('ordem', function($q) use ($search){
                    $q->where('nome', '%' . $search . '%');
                })
                ->orderBy($order, $dir)
                ->get();

            $totalFiltered = Familia::where('nome', 'LIKE', "%{$search}%")
                ->whereHas('ordem', function($q) use ($search){
                    $q->where('nome', '%' . $search . '%');
                })
                ->count();

05 Sep
3 months ago

Penaf left a reply on IsVideo Or IsImage Funcion On Multimedia Model Based On A BelongsTo

The multimedias table is only for images and videos. I was thinking of adding a column isImage on tipos_multimedia table that would be 0 for image and 1 for video (I think it's faster than creating a new table and more relations)

I was asking because I think I saw on some tutorial people having functions similar to the ones I want (isImage and isVideo) for faster verification if a multimedia is an image or a video. But I don't know if that's the faster path

Penaf started a new conversation IsVideo Or IsImage Funcion On Multimedia Model Based On A BelongsTo

Having this model for Multimedia files:

class Multimedia extends Model
{

    protected $table = 'multimedias';

    public $timestamps = false;

    public function tipo_multimedia()
    {
        return $this->belongsTo('App\TipoMultimedia', 'tipo_multimedia_id');
    }

}

Where tipos_multimedias (in english: multimedia types) table has records like this

1 - Images of landscapes
2 - Videos of animals
3 - Videos of landscapes
4 - Images of vertebrate animals

Is it possible to add to Multimedia model function like isVideo and isImage based on what's the ID on tipos_multimedia table?

Or would be simpler to add a tinyint(1) field called isImage on tipo_multimedias tables so I'd know if it was 0 it would be an image and 1 for videos? But for this the first question is still valid.

Thanks in advace!

Penaf left a reply on File Size To Lorge (instead Of Large!)

Dang ... didn't know that!

Always you to the rescue @Cronix!

Thanks mate. Cheers!

Penaf left a reply on File Size To Lorge (instead Of Large!)

You mean I have tu put the mimes rule after the max rule .... right? On my validate I have the max after the mimes

Penaf started a new conversation File Size To Lorge (instead Of Large!)

Hello all, Trying to make a form to upload documents...

Here's my controller DocumentoController.php

    public function store(Request $request)
    {
        $this->validate($request, [
            'ficheiro' => 'required|mimes:pdf,doc,docx|max:1024000',
        ]);

        $documento = new Documento;

        $documento->descricao = $request->get('descricao');

        $ficheiro = $request->file('ficheiro');

        $nome = $ficheiro->getClientOrginalName();

        $extensao = $ficheiro->extension() ?: 'pdf';

        $doc = str_slug($nome) . '.' . str_random(7) . '.' . $extensao;

        $destino = public_path() . '/assets/docs/';

        $ficheiro->move($destino, $doc);

        $documento->pathURL = asset($destino . $doc);


        if ($documento->save()) {
            return redirect('admin/documentos')->with('success', 'Documento criado com sucesso. ID = ' . $documento->id);
        } else {
            return redirect('admin/documentos')->withInput()->with('error', 'Ocorreu um erro ao criar o novo documento.');
        }

And my form on create view

{!! Form::open(array('url' => URL::to('admin/documentos'), 'method' => 'post',  'files' => true, 'class' => 'bf')) !!}
                    <input type="hidden" name="_token" value="{{ csrf_token() }}"/>
                    <div class="row">
                        <div class="col-sm-12">
                            <div class="form-group {{ $errors->first('descricao', 'has-error') }}">
                                {!! Form::label('descricao', 'Descrição') !!}
                                {!! Form::text('descricao', null, array('class' => 'form-control ','placeholder'=> '')) !!}
                                <span class="help-block">{{ $errors->first('descricao', ':message') }}</span>
                            </div>
                            <div class="form-group {{ $errors->first('ficheiro', 'has-error') }}">
                                {!! Form::label('ficheiro', 'Documento') !!}
                                {!! Form::file('ficheiro') !!}
                                <span class="help-block">{{ $errors->first('ficheiro', ':message') }}</span>
                            </div>
                            <div class="form-group">
                                <button type="submit" class="btn btn-success">Criar</button>
                            </div>
                        </div>
                    </div>
                    {!! Form::close() !!}
                

For every pdf I try to upload (doesn't matter if its 150KB or 20MB) I get the error message "File size to lorge" on the file field ... And yes ... it's written "lorge" and not "large" in the error...

I don't seem to be able to debug this ... can anyone help ?

03 Sep
3 months ago

Penaf left a reply on Lookup Table Between Two Models

@Cronix Perfect! Thanks again!

Penaf left a reply on Lookup Table Between Two Models

@Cronix : by the way, you most surelly can help me out with this one (don't know if I should ask a new question instead of asking here...)

On my GalleryController.php I have this:

    public function data()
    {
        $resultados = Galery::all();

        foreach ($resultados as $resultado){
            $resultado->multimedia_count = Galery::images()->withCount('image_id');
        }

    return DataTables::of($resultados)->make(true);
    }

I'm messing up big time am I not?

Penaf left a reply on Lookup Table Between Two Models

@Cronix Thanks mate!

@Tray2 & @newbie360 yup ... images will belong to multiple galleries as well as they might be used on other parts of the application... so having a belongsToMany on the galleries part will leave the db open to more flexibility for the future.

Thanks everybody for the swift and detailed and suggestive answers... as usual ... this community is awesome! :)

Penaf left a reply on Lookup Table Between Two Models

Thanks @staudenmeir @newbie360 and @Cronix for the prompt replies! I'm still very fresh to laravel and dind't understand the mechanics of belongsToMany

About your reply @Cronix ... you are talking about the table names or the ids?

Is this ok?

images
- id

galleries
- id

image_gallery
- id_image
- id_gallery

Penaf started a new conversation Lookup Table Between Two Models

Having 3 SQL tables

images
- id

galleries
- id

images_galleries
-images_id
-galleries_id

How can I relate in the Galeries model the hasMany images?

I have this but doesn't feel like being the correct thing to do:

class Gallery extends Model
{

    protected $table = 'galleries';

    protected $guarded = ['id'];

    public function images ()
    {
        return $this->hasMany('App\Image);
    }


}
16 Aug
3 months ago

Penaf left a reply on Model Names For Weird Table Names

Yeah ... it's driving me nuts @Cronix !

What about for cases like this one:

TABLE: Especie (PK: idEspecie) TABLE: SpecificGroup (PK: idSpecificGroup) TABLE: EspecieSpecificGroup (2 Fields: Especie_idEspeice & SpecificGroup_idSpecificGroup)

I'd rename idEspecie to id ... on the other table idSpecificGroup to id ... what would I do on the table EspecieSpecificGroup? How would I rename those 2 fields since this table only relates entries from the other table?

Penaf started a new conversation Model Names For Weird Table Names

Having inherited a pretty complex mysql database I'm faced with table names that I really don't know how should I name the models for them.

I tried to read naming conventions like this one https://github.com/alexeymezenin/laravel-best-practices#follow-laravel-naming-conventions without reaching any conclusion how should I best name the model.

I have about 30 tables with names like this one:

Table name: JB_CogHospedeiros Field: idCogHospedeiros (Primary Key) Field: descCogHop (varchar 300)

How should I name the model for this table?

Bonus question: Should I make a migration and seed also for future deployments?

Thanks in advance for all the help possible.

03 Jul
5 months ago

Penaf left a reply on Fwrite(): SSL: Broken Pipe / Email

Any solution for this ?

23 May
6 months ago

Penaf left a reply on Pls Help! My Php Artisan Command Has Just Stopped Working. I Get A "[RuntimeException] Directory Name Must Not Be Empty" Error

@Snapey If you say it's pretty early on the bootstrap process ... I trust you :) this is my first big project using laravel.

I haven't change the name of the app. I was making a custom modl and the name colided with a Helper class I had created earlier... after that all hell broke loose!

I'm running php artisan from root of the project and always getting the same error there.

Following a suggestion on other post to add the following code to Container.php

        dump($concrete, debug_backtrace());
        $reflector = new ReflectionClass($concrete);

I now have more debug info to help me, but don't feel I have the expertise required to pinpoint to the exact error. Can you give me a hand here? This is what I'm seing: http://afonsogomes.com/errorDump.html

22 May
6 months ago

Penaf left a reply on Pls Help! My Php Artisan Command Has Just Stopped Working. I Get A "[RuntimeException] Directory Name Must Not Be Empty" Error

Thanks for the reply @Snapey. The thing is that the laravel.log doesn't provide much info to me. Just about a hundred of this:

[2018-05-22 23:22:25] production.ERROR: The "" directory does not exist. {"exception":"[object] (InvalidArgumentException(code: 0): The \"\" directory does not exist. at /home/vagrant/Code/ecocampus/vendor/symfony/finder/Finder.php:547)
[stacktrace]
#0 /home/vagrant/Code/ecocampus/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php(87): Symfony\Component\Finder\Finder->in(false)
#1 /home/vagrant/Code/ecocampus/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php(64): Illuminate\Foundation\Bootstrap\LoadConfiguration->getConfigurationFiles(Object(Illuminate\Foundation\Application))
#2 /home/vagrant/Code/ecocampus/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php(39): Illuminate\Foundation\Bootstrap\LoadConfiguration->loadConfigurationFiles(Object(Illuminate\Foundation\Application), Object(Illuminate\Config\Repository))
#3 /home/vagrant/Code/ecocampus/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(213): Illuminate\Foundation\Bootstrap\LoadConfiguration->bootstrap(Object(Illuminate\Foundation\Application))
#4 /home/vagrant/Code/ecocampus/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(162): Illuminate\Foundation\Application->bootstrapWith(Array)
#5 /home/vagrant/Code/ecocampus/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(146): Illuminate\Foundation\Http\Kernel->bootstrap()
#6 /home/vagrant/Code/ecocampus/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(116): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request))
#7 /home/vagrant/Code/ecocampus/public/index.php(55): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request))
#8 {main}
"} 

Penaf left a reply on Pls Help! My Php Artisan Command Has Just Stopped Working. I Get A "[RuntimeException] Directory Name Must Not Be Empty" Error

This happened to me today also. Can anyone help me ?

Exactly as described, I was also creating a custom model of a database table that already existed.

The model I created was JB_Multimedia.php (code below) the next thing I get this Fatal error: ( ! ) Fatal error: Uncaught ReflectionException: Class view does not exist in /home/vagrant/Code/ecocampus/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 752 ( ! ) ReflectionException: Class view does not exist in /home/vagrant/Code/ecocampus/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 752

Now "php artisan" commands now don't work and I already did a composer update.

Logs are of no help... just plenty of this:

[2018-05-22 21:15:30] production.ERROR: The "" directory does not exist. {"exception":"[object] (InvalidArgumentException(code: 0): The \"\" directory does not exist. at /home/vagrant/Code/myProject/vendor/symfony/finder/Finder.php:547)

Model: JB.Multimedia.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class JB_Multimedia extends Model
{

    protected $table = 'JB_Multimedia';

    protected $primaryKey = 'idMultimedia';

    protected $guarded = ['idMultimedia'];

    public $timestamps = false;

}