tiagotavares

tiagotavares

Web Developer at Cyber-Duck

Porto

Member Since 3 Years Ago

Experience Points 62,780
Experience
Level
Lessons Completed 686
Lessons
Completed
Best Reply Awards 5
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 Jul
5 months ago

tiagotavares left a reply on Laravel .env File Not Changing The Database

Hi,

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

08 Jun
6 months ago

tiagotavares left a reply on 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.

07 Jun
6 months ago

tiagotavares left a reply on Eager Load Relation With Parameters

Hi,

To my knowledge is not possible to pass a parameter to a relation, as referenced:

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

23 Feb
9 months ago

tiagotavares left a reply on 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!

22 Feb
9 months ago

tiagotavares left a reply on 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) === 0) {
        return $query;
    }
        
    if(! $gamesCoexist) {
        return $query->whereHas('machines', function($machines) use($games) {
        foreach($games as $game) {
                $machines->where('game_id', $game);
            }
        });
    }
}
02 Apr
1 year ago

tiagotavares left a reply on 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

27 Mar
1 year ago

tiagotavares left a reply on Return Models Based Upon Pivot Table Data

@JBOWMAN99 Can you mark it as solved?

Thanks! :)

tiagotavares left a reply on Laravel CRUD Generator

Hi,

There are an infinite amount of ways to implement CRUD.

My tips:

  1. Define what you want in the end. Choose a template or prepare to use your own (for example: AdminLTE)
  2. Start with a basic example, 1 table, 1 column type text.
    • Seed it that table. Create the model. Create your controller. Add a resourceful route.
    • Add a map for each of your fields in model, for example:
protected $adminColumns = [
    'name' => 'text'
];
- Start by display all your database table contents in a html table, through the index method. Using the adminColumns.
- 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 :)

tiagotavares left a reply on 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 "<code here>" so it gets formatted (https://help.github.com/categories/writing-on-github/)

tiagotavares left a reply on 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 every time.

You are free to change it for your needs.

tiagotavares left a reply on 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.

07 Mar
1 year ago

tiagotavares left a reply on 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);

tiagotavares left a reply on Return Models Based Upon Pivot Table Data

Maybe something like this?

User::customers()->wherePivot('user_id', $this->id)
        ->wherePivot('created_at', '>=', $start_week)
        ->wherePivot('created_at', '<=', $end_week)
    ->get();

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

09 Aug
2 years ago

tiagotavares left a reply on 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

tiagotavares left a reply on 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.

tiagotavares left a reply on 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!

tiagotavares started a new conversation WhereHas Bug? BelongsToMany

Hello,

I just can't understand why:

  • I need to create an empty Object, instead of using directly the object, that already has the desired id.
  • The first example works, but the second doesn't...
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 HAVE TO QUERY THIS.... and cant use $this
            ->whereHas('users', function ($query) use ($user) {
            $query->where('user_id', $user->id);
        })->exists();
    }
}

The current object already has an id

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

Thanks in advance

06 Oct
3 years ago

tiagotavares left a reply on 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

tiagotavares left a reply on 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 Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\App;
use Mockery\CountValidator\Exception;

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

07 Sep
3 years ago

tiagotavares left a reply on Deploy Laravel 5 To Blocked DocumentRoot With Only Two Folders: Private And Public

Hello!
One of the alternatives is extending the Illuminate\Foundation\Application and overwrite the method publicPath in your application Class.

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

15 Aug
3 years ago

tiagotavares left a reply on 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."

14 Aug
3 years ago

tiagotavares 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