Penaf

Experience

670

0 Best Reply Awards

  • Member Since 4 Months Ago
  • 0 Lessons Completed
  • 0 Favorites

20th September, 2018

Penaf left a reply on Pagination Of Data From A Relation • 3 weeks ago

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 • 3 weeks ago

            $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

19th September, 2018

Penaf left a reply on Using Accessor To Select One Result Of A Related Table • 3 weeks ago

Way better!! Thanks mate!

Penaf left a reply on Using Accessor To Select One Result Of A Related Table • 3 weeks ago

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 • 3 weeks ago

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 • 3 weeks ago

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 • 3 weeks ago

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 • 3 weeks ago

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\... • 3 weeks ago

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 • 3 weeks ago

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\... • 3 weeks ago

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.

12th September, 2018

Penaf started a new conversation Strange Results Using Find() And Where() • 1 month ago

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!

10th September, 2018

Penaf left a reply on Searching Field From Relation Table • 1 month ago

@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 • 1 month ago

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

Penaf left a reply on Searching Field From Relation Table • 1 month ago

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 • 1 month ago

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();

5th September, 2018

Penaf left a reply on IsVideo Or IsImage Funcion On Multimedia Model Based On A BelongsTo • 1 month ago

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 • 1 month ago

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!) • 1 month ago

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!) • 1 month ago

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!) • 1 month ago

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 ?

3rd September, 2018

Penaf left a reply on Lookup Table Between Two Models • 1 month ago

@Cronix Perfect! Thanks again!

Penaf left a reply on Lookup Table Between Two Models • 1 month ago

@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 • 1 month ago

@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 • 1 month ago

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 • 1 month ago

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);
    }


}

16th August, 2018

Penaf left a reply on Model Names For Weird Table Names • 1 month ago

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 • 1 month ago

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.

3rd July, 2018

Penaf left a reply on Fwrite(): SSL: Broken Pipe / Email • 3 months ago

Any solution for this ?

23rd May, 2018

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 • 4 months ago

@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

22nd May, 2018

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 • 4 months ago

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 • 4 months ago

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;

}
Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.