Tray2

Tray2

Oracle Developer (PL/SQL, Forms & Apex) at Scania CV AB

Member Since 4 Years Ago

Solna

Experience Points
189,810
Total
Experience

190 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
1179
Lessons
Completed
Best Reply Awards
123
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 38
189,810 XP
20 Sep
3 days ago

Tray2 left a reply on Do We Need "www." In Site Domains?

You have in reality created two domains so you need to configure socialite to handle both or you can always do something like

$standardDomain = str_replace('www.', '', $domain);

or

$standardDomain = str_replace('https://', 'https://www.', $domain);
19 Sep
4 days ago

Tray2 left a reply on Best Database Management For Speed

None of them.

I'd have two or more tables in one database with a field for each value. That way I can easily do crud for everything and with the proper indexes it will be fast enough. Doing something over a database link is always a bit slower than doing something internal.

When it comes to creating tons of data I might use database transactions since it might be a bit faster not having a commit done on every row.

Tray2 left a reply on The Correct Way To Setup Controller For Info On Index Page

One the homepage I would either go with

$events = Event::latest()->take(5);

or

$events = Event::paginate(5);

Tray2 left a reply on OrderBy() Not Compatible With Distinct()

All sorting and grouping should be done by the database so I suggest you do it in your query instead.

Tray2 left a reply on Kill Not Really Killing (Horizon)

Do you have the correct permissions to kill with the user running the hoizon command?

Tray2 left a reply on Print Automatically With Close The Form

What do you mean by print?

Do you mean sending the data to a physical printer?

Tray2 left a reply on Kill Not Really Killing (Horizon)

My guess is that horizon:purge asks the process to die and that might take some time and sometimes not possible, while kill -9 kills it hard which is almost never the best way.

18 Sep
5 days ago

Tray2 left a reply on How In Testing Switch DatabaseTransactions Off/on On Condition?

I'm using an in memory sqllite dayabase for my tests and so far I have 159 tests and most of those are using RefreshDatabase and they take about 2.5s to run. So unless you use hundreds+ rows for your tests you don't need to worry about performance.

PHPUnit 8.3.4 by Sebastian Bergmann and contributors.

...............................................................  63 / 159 ( 39%)
............................................................... 126 / 159 ( 79%)
.................................                               159 / 159 (100%)

Time: 2.52 seconds, Memory: 34.00 MB

OK (159 tests, 451 assertions)

Tray2 left a reply on Controller Code Vs Model

When I said view I meant a database view

create or replace view some_views as
select something from sometable

This is a eloquent relationship

public function books()
    {
        return $this->hasMany(BookView::class);
    }

Where in my case I connect the genres table with the book_views view. By doing that I can call

$booksOfGenre = $genre->books();

And get all the books that has a certain genre.

So if I do this in my controller

public function show($id)
    {
        $genre = Genre::findOrFail($id);
        return view('genres.show', compact('genre'));
    }

I can then in my view (not database view) do this

@foreach($genre->books as $book)
    {{$book->title}}
@endforeach
17 Sep
6 days ago

Tray2 left a reply on Controller Code Vs Model

It depends like everything else.

I usually only place these in my model.

  • Eloquent relationsjops
  • Get Attributes
  • Set Attributes
class Genre extends Model
{
    public function setGenreAttribute($value)
    {
        $this->attributes['genre'] = ucwords(strtolower($value));
    }

    public function books()
    {
        return $this->hasMany(BookView::class);
    }
}

And keep my eloquent and my validations inside my controllers.

class GenresController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth')->except(['index', 'show']);
    }

    protected function validateGenre(Request $request, $validationRules = [])
    {
        $rules = array_merge([
            'genre' => 'required|unique:genres,genre'
        ], $validationRules);

        $request->validate($rules);
    }

    public function index()
    {
        $genres = Genre::orderBy('genre')->get();
        return view('genres.index', compact('genres'));
    }

    public function show($id)
    {
        $genre = Genre::findOrFail($id);
        return view('genres.show', compact('genre'));
    }

    public function edit($id)
    {
        $genre = Genre::findOrFail($id);
        return view('genres.edit')->with(['genre' => $genre]);
    }

    public function create()
    {
        return view('genres.create');
    }

    public function store(Request $request)
    {
        $this->validateGenre($request);
        $genre = new Genre();
        $genre->genre = $request->genre;
        $genre->save();
        return redirect('/genres')->with('status', $genre->genre . ' successfully added.');
    }

    public function update(Genre $genre, Request $request)
    {
        $this->validateGenre($request, ['id' => 'required|exists:genres']);
        $genre->genre = $request->genre;
        $genre->update();
        return redirect('/genres')->with('status', $genre->genre . ' successfully updated.');
    }

    public function destroy(Genre $genre)
    {
        $genre->delete();
        return redirect('/genres')->with('status', $genre->genre . ' successfully deleted.');
    }
}

It's more a matter of taste in most situations at least for me. If I would have some really complex eloquent or raw SQL i would most likely push it to the model or in the case of the raw SQL push it into a database view. The good thing about the database view is that I can keep my eloquent clean and simple.

By doing this with five tables

            DB::statement(
                "CREATE OR REPLACE VIEW book_views AS
                SELECT a.id author_id, 
                    b.id book_id, 
                    CONCAT(a.last_name, ', ', a.first_name) author_name,
                    b.title,
                    (SELECT ROUND(AVG(s.score), 1) FROM scores s WHERE s.book_id = b.id) rating,
                    b.series,
                    b.part,
                    b.released,
                    g.id genre_id,
                    g.genre,
                    f.id format_id,
                    f.format,
                    CASE series
                        WHEN 'Standalone' THEN b.released
                        ELSE (SELECT MIN(bi.released) FROM books bi WHERE bi.series = b.series) 
                    END series_started
                FROM authors a,
                    books b,
                    genres g,
                    formats f
                WHERE a.id = b.author_id
                AND   b.genre_id = g.id
                AND   b.format_id = f.id"
            );

I can still use a pretty simple eloquent query in my controller

    public function index()
    {
        $books = BookView::orderBy('author_name')
                         ->orderBy('series_started')
                         ->orderBy('part')
                         ->orderBy('released')
                         ->orderBy('title')
                         ->get();
        return view('books.index')->with('books', $books);
    }

However like I said before it's a matter of your preference or in worst case a matter of coding convention used by the company you are working for..

16 Sep
1 week ago

Tray2 left a reply on Is It Okay To Have Three Foreign Keys In A Pivot Table?

I would go with two pivots one for model_toy and one for child_toy.

Since there can be toys that no child yet owns.

Tray2 left a reply on After Copying A Laravel Project Blade Views Not Reflecting Changes

First of all get some proper version control like git which is free.

https://git-scm.com/

You can try running php artisan view:clear to clear all cached views.

Tray2 left a reply on Is Mass Assignment Dangerous ?

It can be dangerous yes.

Let's say you have a column called is_admin in your users table and you haven't set the fillable array or set guarded to an empty array, then the malicious user can send a request where he passes the is_admin = 'Y' and he is admin on your site.

So as a rule of thumb

$user = new User(Input::all());

is bad practice. I would do something like this instead

$user = new User($request->validate([
    'username' => 'required',
    'email' => 'required|email',
    'password' => 'required'
]);

That way only the validated fields are passed into the table.

15 Sep
1 week ago

Tray2 left a reply on How In Testing Switch DatabaseTransactions Off/on On Condition?

You can also use RefreshDatabase which refreshes the database every time.

Tray2 left a reply on Column Not Found: 1054 Unknown Column '_method' In 'field List'

You are trying to update fields in the database that does not exists.

You are probably doing $request->all() in your controllers update method. That is bad practice and can be a security risk.

If you have done protected $guarded = []; in your model you need to make sure only the fields you want are used. You can do that easiest by validating the necessary fields

Or doing protected $fillable = ['title', 'body']; in your model.

Tray2 left a reply on My Factory Is Not Applied To My Test Cases

That depends, I would not use transactions unless it is critical that more than one database action needs to complete successfully.

Let's say you have a bank and you want to transfer funds from one account to another.

  1. Deduct the amount from the source account.
  2. Add the amount to the destination account.
  3. If both actions finish ok commit it else rollback.

So if you have that kind of need use transactions otherwise I would suggest that you don't use it.

Somethings to be aware of is that transactions can cause deadlocks in your database. This is normal behaviour but you need to handle it.

https://laravel.com/docs/6.x/database#database-transactions

14 Sep
1 week ago

Tray2 left a reply on Store Options In Database

Yes that would work too.

Tray2 left a reply on Store Options In Database

So you are receiving this?

question_id = 1
answer1 = 'Some answer'
answer1_correct = false
answer2 = 'Some other answer'
answer2_correct = false
answer3 = 'Some correct answer'
answer3_correct = true
answer4 = 'Some other wrong answer'
answer4_correct = false

If so then something like this should store them for you

$answer1 = new Answer();
$answer1->answer = $request->answer1;
$answer1->is_correct = $request->answer1_correct;
$answer1->question_id = $request->question_id;
$answer1->save();

$answer2 = new Answer();
$answer2->answer = $request->answer2;
$answer2->is_correct = $request->answer2_correct;
$answer2->question_id = $request->question_id;
$answer2->save();

//and so on for answer 3 and 4

Edit: Forgot the question_id.

Tray2 left a reply on Query Efficiency

First of all I suggest you refactor that code into smaller functions since this is barely eligable.

At first glance I Noticed that you are using the Auth facade and helper multiple times-

    if(Auth::check()) {
      $userType = Auth::user()->user_type;
      $user = auth()->user();
      $users = User::all();
      $player = auth()->user();
      $players = $users->where('team_id', Auth::user()->team_id)->where('user_type', 'player');

I suggest you use a middleware on the route instead

Route::get('/', '[email protected]')->middleware('auth'):

Then you don't have to do the first if statement.

Doing this is almost never good. Try to limit what you load or break it out into a service that feeds the view with ajax.

$model = Model::all();

You can assign Auth::user() to a variable then you don't have to call it every time.

$user = Auth::user();

The $user and the $player contains the same thing remove one of then

$players = Players::where('team_id', $user->team_id)->where('user_type', 'player');

How many genders do you have? I guess no more than three (M, F, O);

These can be hardcoded in the view since it's very unlikely that they will increase. Store the gender in the users table.

This can be moved to the view.

$team = $user->team;

Make sure you have indexes on the columns you use in your selects

  • *.team_id
  • users.user_type
  • created_at
  • games.id
  • game_assignments.game_id
  • game_assignments.statistician_id
  • stats_done

You also really should have a controller for each model and not one big controller for them all, that way you only pull the data you need for each view instead of pulling everything like you are doing now.

Tray2 left a reply on Store Options In Database

Simple

Create a form the has four fields with answers and a field telling which is the correct answer.

Tray2 left a reply on My Factory Is Not Applied To My Test Cases

Is the filename userFactory.php or UserFactory.php?

If it's the first rename it to the second.

Tray2 left a reply on Query Efficiency

Yes, how else would we be able to help you?

13 Sep
1 week ago

Tray2 left a reply on Translate Database

Do you mean that if you pull the English word Help from the database you want to translate it to let's say the German word for help, Hilfe?

Or do you want to display the data you received from the database in a view?

If it's the first then I suggest you translate it beforehand and store a copy of each in the database.

If it's the second one I really suggest you watch Laravel From Scratch

https://laracasts.com/series/laravel-from-scratch-2018

or the Laravel 6 From Scratch here

https://laracasts.com/series/laravel-6-from-scratch

Tray2 left a reply on Query Efficiency

Can you share the code that generates the query?

There are a lot of tricks with Eloquent that can help you. This talk from Laracon is a good start. https://www.youtube.com/watch?v=IBUXXErAtuk

If you can't get it to work I suggest you use plain ol' SQL.

12 Sep
1 week ago

Tray2 left a reply on FORGE IS DOWN

Don't think anyone on here has access to the servers so we can't help you.

Have you tried twitter or discord

https://twitter.com/laravelphp

https://discord.gg/mPZNm7A

Tray2 left a reply on Should I Make Special Migrations Just For Tests?

You should not use special migrations for testing since that kinda defeats the purpose.

However sometimes you might need to compensate for the differences between the different databases.

If you have issues with SQLite you can always set up a testing database in MySQL.

11 Sep
1 week ago

Tray2 left a reply on Use Flash Message In Blade Template

I your controller methods you can do this

return redirect('dashboard')->with('success', 'Profile updated!');

You should use {{ }} instead of {!! !!}

09 Sep
2 weeks ago

Tray2 left a reply on MySQL View With Prepared Bindings

When creating database views I use a regular migration like this.

public function up()
{
    DB::statement(
                "CREATE OR REPLACE VIEW book_views AS
                SELECT b.id, 
                    CONCAT(a.last_name, ', ', a.first_name) author_name,
                    b.title,
                    b.series,
                    b.part,
                    b.released,
                    g.genre,
                    f.format
                FROM authors a,
                    books b,
                    genres g,
                    formats f
                WHERE a.id = b.author_id
                AND   b.genre_id = g.id
                AND   b.format_id = f.id"
            ); 
}

Tray2 left a reply on Why `Framework Running` Taking Too Much Time?

Yes it would.

When using eloquent you might hit the database more than strictly necessary.

If you have three tables and you use eloquent to join them you might end up hitting the database hundreds or even thousands of times instead of the desired one time. The Laravel Debug bar or Telescope will help you catch these cases. In these cases it might be better to use plain SQL to get the data you need.

08 Sep
2 weeks ago

Tray2 left a reply on How To Make Image Zoom When Mouse Is Placed Over Like This Website

You can do that with plain CSS

 <style>
.zoom {
  padding: 50px;
  background-color: green;
  transition: transform .2s; /* Animation */
  width: 200px;
  height: 200px;
  margin: 0 auto;
}

.zoom:hover {
  transform: scale(1.5); /* (150% zoom - Note: if the zoom is too large, it will go outside of the viewport) */
}
</style>

<div class="zoom"></div> 

Tray2 left a reply on How Can I Make This Code More Simple?

Don't store json in your database if you can avoid it. It's better to have fields for each value.

Tray2 left a reply on Why `Framework Running` Taking Too Much Time?

I would suggest you do the following

  • Check your eloquent are running hundreds of queries try eagar loading (If laravel 6 lazy eagar loading)
  • Add indexes where needed to your tables
  • Consider using SQL over Eloquent relationships
  • If you don't want SQL in your queries use database views.
07 Sep
2 weeks ago

Tray2 left a reply on Form Is Not Being Posting To The Intended Route, What Should I Double Check

Like @nakov said don't use the same route for more than one thing.

Route::get('/', '[email protected]');
Route::post('/', '[email protected]');

Or if you are lazy you can use

Route::resource('somemodel', 'SomeController');

Tray2 left a reply on FormRequest Inside A Package?

In the top one you tell php that the parameter $request must be an instance of SubscribeNewsletter and in the second one it must be an instance of Request. You need to use the instance your code expects.

Tray2 left a reply on Upgrading To Laravel 6.0 On OSX Failed Due To PHP HHVM Version

Then remove HHVM and run php-fpm instead.

Tray2 left a reply on How To Save Nested Associate Records?

Somethng like this should do the trick.

$model1 = new Model1();
$model1->whatever = $request->whatever;
$model1->save();

$forech($request->whatnot as $whatnotRow) {
    $whatnot = new Whatnot();
    $model2->whatnot = $whatnotRow;
    $model2->save();
}

Tray2 left a reply on How To Eliminate Spaces Introduced By "@" Tags In Blade?

You could do a in your master

@yield('meta')

Then use

@section('meta')
    @if(isset($categoryName))
            <meta property="og:url" content="https://www.my-domain.com/{{$categoryName}}">
    @else
        <meta property="og:url" content="https://www.my-domain.com/latest">
    @endif
@endsection

Tray2 left a reply on How To Eliminate Spaces Introduced By "@" Tags In Blade?

I don't think there is a blade issue but rather has to do with the way you have written your code.

This should probably work better.

 @if(isset($categoryName))
        <meta property="og:url" content="https://www.my-domain.com/{{$categoryName}}">
 @else
       <meta property="og:url" content="https://www.my-domain.com/latest">
 @endif

Tray2 left a reply on How To Protect My Laravel Project Source Code?

I would not recommend it since it will slow down your site, however that is up to you to make that trade off.

It's much better to host it on a server only you have access to.

I don't think there are any free alternatives at least not any found in the few minutes.

Read this article on protecting you php source code

https://www.phpclasses.org/blog/package/9574/post/1-PHP-Source-Code-Protection-Solutions.html

Tray2 left a reply on How To Protect My Laravel Project Source Code?

Depends on what you mean by protecting.

A properly set up hosting will never display the php source code.

You really can't protect the source code from someone who has direct access to the server. At least not if you expect to have good performance on the site.

06 Sep
2 weeks ago

Tray2 left a reply on Best Practise: Jobs For Very Long Processes

That amount of records should only take seconds to complete.

I suggest you take a look at the code for it.

What database are you using? Are you using transactions?

Tray2 left a reply on Eloquent : How To Store Object In Table

I would try to store as little json in my database as possible.

The only time I would store it as json is if I need to pass it to a javascript as json and nothing else.

02 Sep
3 weeks ago

Tray2 left a reply on Multiple Websites In Laravel

I would go with option number 3. The server going down issue is not really an issue if you are setting up your environment with a load balancer and at least two web servers.

01 Sep
3 weeks ago

Tray2 left a reply on Help In Editing A Form With Drop Down Selection

Yes regular html form syntax. Much easier to read manipilate and debug.

Tray2 left a reply on Use InnerJoin With A "complex" SQL Request

Try using

DB::select('<your query here>');

Tray2 left a reply on Help In Editing A Form With Drop Down Selection

I would do something like this.

<select name="leave_type">
    @foreach($leaveTypes as $leaveType)
        <option 
            value="{{ $leaveType->id }}" 
            @if($leaveType->id == $employe->leave_type_id)
                 {{'selected' }} 
            @endif >
            {{ $leaveType->type }}
        </option> 
    @endforeach
</select>

and don't forget to stop using the laravelcollective form shit.

Tray2 left a reply on Convert Input Into Template

Try with

@error($name)
@error('title')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror

The {{ $name }} = <?php echo $name; ?>

Tray2 left a reply on Namespace Declaration Statement

Your file shoul look something like this

<?php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Author;

class AuthorControllerTest extends TestCase

So move the namespace to just below the <?php tag.

Tray2 left a reply on Bootstrap Or Uikit

If I want something quick to demo I use Bootstrap and if I want the most flexibility I use Tailwind.