tiagotavares

Web Developer at Cyber-Duck

Experience

57,980

5 Best Reply Awards

  • Member Since 3 Years Ago
  • 642 Lessons Completed
  • 34 Favorites

12th July, 2018

tiagotavares left a reply on Laravel .env File Not Changing The Database • 3 months ago

Hi,

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

8th June, 2018

tiagotavares left a reply on Self Relation On Model With Date Constraint - Possible? • 4 months ago

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.

7th June, 2018

tiagotavares left a reply on Eager Load Relation With Parameters • 4 months ago

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

23rd February, 2018

tiagotavares left a reply on SQL Query To Eloquent • 7 months ago

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!

22nd February, 2018

tiagotavares left a reply on SQL Query To Eloquent • 7 months ago

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

2nd April, 2017

tiagotavares left a reply on Need Help For Naming Eloquent Relations • 1 year ago

Hey! I would probably go with something like this:

xxx -> eventsAsOrganiser yyy -> eventsAsParticipant

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

Hope it helps

27th March, 2017

tiagotavares left a reply on Return Models Based Upon Pivot Table Data • 1 year ago

@JBOWMAN99 Can you mark it as solved?

Thanks! :)

tiagotavares left a reply on Laravel CRUD Generator • 1 year ago

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

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

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

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

7th March, 2017

tiagotavares left a reply on Diplay Activity Where User Has Replied To • 1 year ago

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 Many To Many Relationship • 1 year ago

@tjkalinowski That's it

tiagotavares left a reply on Return Models Based Upon Pivot Table Data • 1 year ago

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

9th August, 2016

tiagotavares left a reply on WhereHas Bug? BelongsToMany • 2 years ago

@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 • 2 years ago

@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 • 2 years ago

@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 • 2 years ago

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

6th October, 2015

tiagotavares left a reply on How To Route Multilingual Website • 3 years ago

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

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

7th September, 2015

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

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

15th August, 2015

tiagotavares left a reply on ReflectionException • 3 years ago

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."

14th August, 2015

tiagotavares started a new conversation ReflectionException • 3 years ago

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

Edit Your Profile
Update

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