tiagotavares

tiagotavares

Web Developer at Cyber-Duck

Member Since 4 Years Ago

Porto

Experience Points
65,330
Total
Experience

4,670 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
711
Lessons
Completed
Best Reply Awards
5
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    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 Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 14
65,330 XP
Jul
12
1 year ago
Activity icon

Replied to Laravel .env File Not Changing The Database

Hi,

Try running: php artisan config:cache to reload the new values from the .env file.

Hope this helps

Jun
08
1 year ago
Activity icon

Replied to Self Relation On Model With Date Constraint - Possible?

Hi @mfoote this is happening because your model doesn't have any data since you are using the Facade.

This ->where('start_time', '<', $this->start_time) needs to be moved from your relation into a scope.

E.g.

public function _previous_calls()
{
    return $this->hasMany('App\Call', 'ani', 'ani');
}

public function scopeHappeningBefore($query, $date) {
    return $query->where('start_time', '<', $date);
}

You can use this on your Controller like this, e.g.:

...
 '_previous_calls' => function ($query) use($date) {
    return $query->happeningBefore($date);
},
...

This will return you all the Calls before the received date.

Hope this is what you are looking for.

Jun
07
1 year ago
Activity icon

Replied to Eager Load Relation With Parameters

Hi,

To my knowledge is not possible to pass a parameter to a relation, as referenced on the other comment.

I think the logic you are looking for is loading the relationship (reading) and query the proper one based on the date you have available:

Machine model

public function firstReading()
{
    return $this->hasOne(Reading::class)
        ->where('date', '>', $this->first_reading_date);
}

Reading model

public function scopeNearestTo($query, $date) {
    return $query->orderByRaw("ABS(DATEDIFF(date, '{$date}'))");
}

Controller/Usage

$date = Carbon::createFromFormat('d-m-Y', $date)->format('Y-m-d');

Machine::select('location_id', 'id', 'code_id', 'first_reading_date', 'first_reading_in', 'first_reading_out', 'code_id')->with([
    'firstReading' => function ($query) use($date) {
        $query->nearestTo($date);
    }
]);

Let me know if there are any typos. And if this is what you expect.

**Edit -> Quite similar to the previous answer.

Feb
23
1 year ago
Activity icon

Replied to SQL Query To Eloquent

Didn't understood the requirements properly, I think this scope solves your problem.

return $query->where(function($location) use($games) {
    foreach($games as $game) {  
        $location->whereHas('machines', function($query) use($game) {
            $query->where('game_id', $game);
        });
    }
});

Cheers!

Feb
22
1 year ago
Activity icon

Replied to SQL Query To Eloquent

Hey!

If I got it right you want all locations that have the all the games from the array you are passing in as parameter of the scope (when games can't coexist).

If that is the case:

public function scopeWithGames($query, $games, $gamesCoexist)
{
    if(! count($games)) {
        return $query;
    }

    if($gamesCoexist) {
        return $query->whereHas('machines', function($machines) use($games) {
            foreach($games as $game) {
                $machines->where('game_id', $game);
            }
        });
    }
        
    return $query->whereHas('machines', function($machines) use($games) {
        $machines->whereIn('game_id', $games);
    });
}

Hope this helps

Apr
02
2 years ago
Activity icon

Replied to Need Help For Naming Eloquent Relations

Hey! I would probably go with something like this:

xxx -> eventsAsOrganiser

yyy -> eventsAsParticipant

$user->events();
$user->eventsAsOrganizer();
$user->eventsAsParticipant();

Hope it helps

Mar
27
2 years ago
Activity icon

Replied to Return Models Based Upon Pivot Table Data

@JBOWMAN99 Can you mark it as solved?

Thanks! :)

Activity icon

Replied to Laravel CRUD Generator

Hi,

There are lots of ways to implement CRUD. Always depends on your needs.

Some tips:

  1. Define what you want in the end. Choose a template or prepare to use your own (for example: AdminLTE), what fields do you need, etc...

  2. Start with a basic example, 1 table, 1 column type text.

    2.1. Seed it that table. Create the model. Create your controller. Add a resourceful route.

    2.2. Add a map for each of your fields in model, for example: protected $adminColumns = ['name' => 'text']; .

    2.3. Start by display all your database table contents in a html table, through the index method. Using the adminColumns.

    2.4. The the show, update, destroy, .... methods.

After the easy part, start to abstract each part one by one. Add textareas, images. For example create a Class to handle the stores and updates to database, one to display data in the form. Add a trait on your model to easier implementation on other ones. Add CRUD commands.

Basically one step at a time.

Hope it helps :)

Activity icon

Replied to Authentification Not Working In Laravel 5.4

Hey,

Is your profile route inside the web middleware?

Can you show your routes file? By default routes/web.php

Tip place your code inside the proper format: https://help.github.com/articles/creating-and-highlighting-code-blocks/

Activity icon

Replied to Purpose Of Using Web Middleware When Saving Session

Hey,

As you can see from the docs https://laravel.com/docs/5.4/middleware#middleware-groups , the web is a an alias for easier reference in the routes and \Illuminate\Session\Middleware\StartSession::class is part of it.

It contains some just some boilerplate so you don't need to worry about the basic initialisation for "normal" web requests each time.

You are free to change it for your needs.

Hope this helps!

Activity icon

Replied to On Post 500 Internal Server Error

Check your laravel.log to get more details about this error, or check the preview of request in chrome.

If you still didn't solved it share those details here :)

Mar
07
2 years ago
Activity icon

Replied to Diplay Activity Where User Has Replied To

Something like this?

$activities = Activity::with('Trainer.Avatar', 'Comments.Trainer.Avatar')
        ->where('userid', '=', $trainerid)
        ->orWhereHas('Comments.Trainer', 
            function($commentsTrainer) use($trainerid) 
            {
                    $commentsTrainer->where('id', $trainerid);
            })
        ->where('date_deleted', '=', '0')
        ->orderBy('date_last_activity', 'desc')
        ->paginate(10);

Check this https://laravel.com/docs/5.4/queries#parameter-grouping

Activity icon

Replied to Return Models Based Upon Pivot Table Data

Maybe something like this?

User::find($id) // can be replaced by $this of the example you provided
    ->customers() // belongsToMany
    ->wherePivot('created_at', '>=', $start_week)
    ->wherePivot('created_at', '<=', $end_week)
    ->get();

https://laravel.com/docs/5.4/eloquent-relationships#many-to-many

Aug
09
3 years ago
Activity icon

Replied to WhereHas Bug? BelongsToMany

@pmall You are totally right! Thanks!

"Which is also strange. Why would you ever check those two models are associated? I guess there is a lot of misunderstanding here but can't figure out what.".

I need to check if the models are associated to either show them as acquired or not. The way you suggested is the correct one since I already have the relationship eager loaded. (Using where is ridiculous)

Thanks again

Activity icon

Replied to WhereHas Bug? BelongsToMany

@pmall This is a many-to-many relationship, a card may belong to multiple users and users may have multiple cards. So $user->cards return multiple cards.

Activity icon

Replied to WhereHas Bug? BelongsToMany

@pmall I know there is other ways of reaching the desired value. And in this case, you are right the correct way is:

    public function isCompleted($user)
    {
        return $this->users()->where('id', $user->id)->exists();
    }

@AkiyamaSmart I didn't understand what you wrote at first (missing commas ;) ), but now it all makes sense. where and whereHas are supposed to filter eloquent models, if I already have the filtered model to 1 record/eloquentItem, there is no need to filter it.

Thank you both!

Activity icon

Started a new Conversation WhereHas Bug? BelongsToMany

Hello,

I just can't understand why, I need to create an empty Object, instead of using $this.

The first example works, but the second doesn't... The second returns true because it ignores the current object id

class Card extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class, 'card_user', 'card_id', 'user_id');
    }

    public function isCompleted($user)
    {
        return (new static)->where('id', $this->id) // No idea why i need to create a new instance.... and cant use $this
            ->whereHas('users', function ($query) use ($user) {
            $query->where('user_id', $user->id);
        })->exists();
    }
}
    public function isCompleted($user)
    {
        return $this->whereHas('users', function ($query) use ($user) {
            $query->where('user_id', $user->id);
        })->exists();
    }

Thanks in advance

Conclusion:

@AkiyamaSmart I didn't understand what you wrote at first (missing commas ;) ), but now it all makes sense. where and whereHas are supposed to filter eloquent models, if I already have the filtered model to 1 record/eloquentItem, there is no need to filter it.

Oct
06
4 years ago
Activity icon

Replied to How To Route Multilingual Website

In that case you should have two routes, 1 for both parameters and 1 when one is missing (Even better would be to create a localeMiddleware)

Routes File:

get('{localeOrPage?}', [
    'as'   => 'page',
    'uses' => 'PagesController@showPage'
]);

get('{locale}/{page}', [
    'as'   => 'page',
    'uses' => 'PagesController@showPageLocale'
]);

Controller

<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Support\Facades\App;

class PagesController extends Controller
{

    public function showPage($locale = 'en')
    {
        $availableLocale = ['pt', 'en', 'es', 'fr'];

        if (!in_array($locale, $availableLocale)) {
            // passed page as first argument
            return $this->showPageLocale('en', $locale);
        }

        // didn't pass the page
        return $this->showPageLocale($locale);
    }

    public function showPageLocale($locale, $page = 'about')
    {
        $this->setLocale($locale);

        return $this->view($page);
    }

    private function setLocale($locale)
    {
        $availableLocales = ['pt', 'en', 'es', 'fr'];
        App::setLocale(in_array($locale, $availableLocales) ? $locale : 'en');
    }

    private function view($page) {
        $existingPages = ['about', 'products', 'clients', 'services', 'contact'];

        if (!in_array($page, $existingPages)) {
            throw new \Exception(); // Create your exception (ex: PageDoesNotExistException)
        }

        return view('pages.' . $page);
    }
}

Hope it helps

Activity icon

Replied to How To Route Multilingual Website

Hi,

To solve your problem you just need to set the default value for $page parameter in your showPage method.

...
public function showPage($locale, $page = 'about') 
...

Personal tip: From my perspective your code could be cleaner, you could place 1 route for each page, or simply:

<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Support\Facades\App;

class PagesController extends Controller
{

    public function showPage($locale, $page = 'about')
    {
        $this->setLocale($locale);

        return $this->view($page);
    }

    private function setLocale($locale)
    {
        if ($locale) {
            App::setLocale($locale);
        }
    }

    private function view($page)
    {
        $existingPages = ['about', 'products', 'clients', 'services', 'contact'];

        if (!in_array($page, $existingPages)) {
            throw new \Exception(); // Create your exception (ex: PageDoesNotExistException)
        }

        return view('pages.' . $page);
    }
}

Hope it helps

Sep
07
4 years ago
Activity icon

Replied to Deploy Laravel 5 To Blocked DocumentRoot With Only Two Folders: Private And Public

Hello!

Explanation

As the fire command used in php artisan serve command uses your laravel/application instance to change to the public folder (with chdir) and it returns an Exception because the folder does not exist in your base directory.

Illuminate\Foundation\Console\ServeCommand

...
public function fire()
    {
    // This changes the work directory. Accessing method publicPath in Class Illuminate\Foundation\Application
        chdir($this->laravel->publicPath());
    
        ...
    }
...

Illuminate\Foundation\Application

class Application extends Container implements ApplicationContract, HttpKernelInterface
{
    ...
    public function publicPath()
    {
        return $this->basePath.DIRECTORY_SEPARATOR.'public';
    }
    ...
}

Possible Solution

One of the alternatives is extending the Illuminate\Foundation\Application and overwrite the method publicPath() in your new application Class (Tested with Laravel 5.1).

You can create a new file for in your app folder for example app/MyApplication.php extending Illuminate\Foundation\Application

<?php namespace App;

use Illuminate\Foundation\Application;

class MyApplication extends Application
{

    public function publicPath()
    {
        // Your new public path
        return realpath($this->basePath . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'public');
    }
}

After this you only need to change the Class to create your app in bootstrap/app.php

// Replace this
/*$app = new Illuminate\Foundation\Application(
    realpath(__DIR__ . '/../')
);*/

$app = new \App\MyApplication(
    realpath(__DIR__ . '/../')
);

Hope it helps!

Regards
Tiago Tavares

Aug
15
4 years ago
Activity icon

Replied to ReflectionException

Got an answer in StackOverflow that solved my problem

"Run composer dump-autoload on your server. This will rebuild the autoloader cache, that stores paths to classes. If your paths are different locally and on the server, this could help."

Aug
14
4 years ago
Activity icon

Started a new Conversation ReflectionException

I developed an application with Laravel version 5.1 using homestead to test. Now when i place it on the production server I get this error that i can't replicate on the local machine.

ReflectionException in Container.php line 736
Class MyMultiSelect does not exist

This class is a sleeping-owl Custom Form Item http://sleeping-owl.github.io/en/Form_Elements/Custom_Form_Elements.html

I checked for:

  • namespace errors / conflicts - I even placed the class in the global namespace
  • tried to load the file containing the class in composer.json

Filename: MyMultiSelect.php Class: MyMultiSelect namespace: Global so to access it \MyMultiSelect

admin/bootstrap.php

FormItem::register('myMultiSelect', \MyMultiSelect::class);

Can anyone help me? Thanks!