andonovn

andonovn

Member Since 3 Years Ago

Burgas

Experience Points 98,910
Experience Level 20

1,090 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 676
Lessons
Completed
Best Reply Awards 51
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.

23 May
2 months ago

andonovn left a reply on Having Difficulties Setting Up Amazon AWS SQS Queues

@GEORGEINGGS - Just small thing that's not really related to the initial issue but may be of a help for someone who may try to copy/paste your code: The env() helper must not be used outside config files. Instead, we should use the config() helper which reads from the config. That's because when in production you use the php artisan config:cache command, you will end up having unexpected behaviour from your env() references outside the config files.

I know it's a very old thread but just wanted to eventually save someones future troubles.

09 Mar
4 months ago

andonovn left a reply on Looking For Tutor/mentor Or Studybuddy

@raphaello3453 I can help you with code reviews and answering your questions :) As for Skype calls, the best I can find time for is ~2hours session once per week. I am not looking to be paid or something, everything I offer is for free. Just keep in mind I am not a native speaker.

22 Feb
5 months ago

andonovn left a reply on Command Bus Pattern Vs Repository Service Pattern

If you know the pros and cons of both, you should be able to decide on your own which one to use. Of course depending on the project you are working on, and what problems you are trying to solve. In case you are not confident enough to take that decision, there are several videos here on Laracasts which you can reference to, and experiment a little bit on a dummy project of yours. Most, if not all, design patterns are both language-agnostic and framework-agnostic, so it doesn't really matter if you are using Laravel 5.7, Ruby on Rails, Django, etc.

22 Jan
6 months ago

andonovn left a reply on Laravel Blade Pasing Json To Vue Component

How about :data="{{ json_encode($data) }}" or :data="@json($data)"?

19 Jan
6 months ago

andonovn left a reply on Laravel 5.4 - Creating New Model And Attach Data To PIVOT

I feel like you are not copy/pasting the code that leads to the error you have quoted. In my eyes, I believe the posted code will throw an exception for undefined variable $users from inside the addGroup method. I don't see this variable declared/passed anywhere. Another thing is why would you call ->members()->attach() from both your controller and the addGroup method? Again, doesn't make any sense. Save your files, then run the code and post the error you see in case you can't figure it out. Then we may help :)

And if I were you, I would simplify this piece of code. All you need is

// Only after validation

$group = Group::create([
    'name' => strtolower($request->input('group_name')),
        'slug'=> str_slug(strtolower($request->input('group_name'))),
        'user_id'=> auth()->id(),
]);

$model->members()->attach($request->input('users'));

in your controller. Don't get me wrong, there is nothing wrong if you want to move this logic to the model, but first put it in the controller and make sure it works. Then you can easily move it to the model if you want to.

30 Nov
7 months ago

andonovn left a reply on Where To Add The Css And Js In A Laravel /Vue SPA?

Thanks for the kind words, that made my day :)

28 Nov
7 months ago

andonovn left a reply on Where To Add The Css And Js In A Laravel /Vue SPA?

@boubou what you have described is absolutely doable even in a single Laravel application. I guess by ‘backend’ you meant an admin dashboard? If I got you right, let me tell you the fastest way to achieve that. Let’s say you have just installed a fresh Laravel instance. Here’s all you have to do:

  1. Rename the example vuejs component to TheApp.vue or something similar which will act as your single js entry point
  2. On your welcome.blade.php register all your js/css both for your front end and admin panel in the head of the html. For the body just use ‘<the-app></the-app>’, of course wrapped in a div with an id of ‘app’ so vue can know about it.
  3. Use Vue Router and register all your routes, including both the front end and the admin panel.

However, keep in mind that a better approach would be to separate the app in two different apps: One for the SPA, build in VueJs using their CLI so you can leverage more of their ecosystem. This will again include both the front end and the admin panel as single SPA. And you can use Laravel only for the backend of your SPA. But don’t think of backend as admin dashboard, but as API backend, which will accept requests both from your front end and admin panel, and will serve json responses.

26 Nov
7 months ago

andonovn left a reply on Problem With Laravel:auth

Simple as Auth::loginUsingId(789); in case you are using the default session based authentication.

A more complete example, say we have a login form being submitted. Here is how our controller may look like:

$request->validate([
    'email' => 'required|exists:users',
    'password' => 'required',
]);

if (! app(\Path\To\ExternalLoginServiceClass::class)->hasValidCredentials($request->email, $request->password)) {
    throw \Illuminate\Validation\ValidationException::withMessages([
        'email' => 'Invalid credentials',
    ]);
}

\Auth::loginUsingId(
    \App\User::whereEmail($request->email)->first()->id
);

return back();

More info in the official docs

andonovn left a reply on How To Activate Btn:hover!

Basically, if I got this right, what you are looking for is to simulate the hover with JS in order to apply the CSS you already have. But unfortunately, that's not possible because it's not considered a trusted event. So I believe you don't have a much of a choice here other than duplicating the CSS. More info on the topic in SO question

andonovn left a reply on Where To Add The Css And Js In A Laravel /Vue SPA?

It doesn't make much sense to place them inside the .vue files.

Since it is SPA, you should have just one blade (or why not plain php) file which should contain the initial HTML rendered by the browser. So that's the perfect place to load most of your JS/CSS files

15 Sep
10 months ago

andonovn left a reply on No Query Results For Model [App\Requisition].

Do you have a record in your requisitions table with an ID of 5?

If you have enabled soft deletes, make sure the deleted_at column is null for that record

01 Sep
10 months ago

andonovn left a reply on Ajax Request Throws Methodnotallowed Exception

@SmokeTM Most probably your article/vote endpoint is defined with the wrong method in your routes file (can be routes.php if you are using an older version, or web.phpor api.php in the new ones). So just open it and make sure it's registered as post because from what I can see that's how you utilise it from your frontend.

By the way, a quick tip to check it faster is to run php artisan routes:list | grep vote in your terminal. That would list you all your endpoints containing vote in their urls or names, and each line will contain the associated http verb

andonovn left a reply on Company Change At Nav Level

Oh, I see! I knew it may be something weird like that tho :)

You are welcome :)

31 Aug
10 months ago

andonovn left a reply on Laravel + Wordpress Connection

Oh, I didn't know you can change the WP passwords hashing algorithm, that's a nice feature :) And sorry that I can't be of a help, really not familiar with that kind of packages, plugins, etc. But if you already managed to solve the problem and it's working great, then to be honest I wouldn't be looking for a package if I were you :D

andonovn left a reply on Laravel + Wordpress Connection

@goncalolopes The problem I can see this way is that the user won't be able to authenticate himself/herself when using the WP login. Because you are hashing using your Laravel (bcrypt) algorithm. And WP would hash the password in a different way. Not sure if that's a problem for you, tho, because you may only need the user to appear visually in WP. But in case you want to allow WP logins, then you can simply create an endpoint in your Laravel app which will accept a user/pass and will check if you have an existing user with the provided password in your Laravel database and will return accordingly. Then you can hook into WP's build-in hook after login fail (not sure how it's called) and utilise your Laravel endpoint to decide if the provided credentials are correct, so you can manually log the user in. Of course for security reasons make sure to create a simple random long string to be used as an API token, and copy/paste it in both projects. So you can be sure that only you can access that endpoint.

andonovn left a reply on Cant Install A Working Existing Project

@dabnad Maybe you are somehow overseeing the error but it clearly says what's wrong: It is unsafe to run Dusk in production.

Are you excluding your dev dependencies on your production server? What I mean is you should run composer install --no-dev instead of just composer install.

Another reason for the problem to occur is if you don't have an .env file on the server you are installing the project. In Forge you can easily control the .env file by visiting Sites (from the top nav bar) -> the site you want to install -> Environment (from the left menu) -> Edit environment

andonovn left a reply on Company Change At Nav Level

@dan3460 I believe all you need is to put View::share('companies', $companies) in a service provider. Here is an example from the docs

By the way, most probably your id should be user_id. Because it doesn't really make much sense to query against the id column in the assignments for a user id. But I don't really know what you are building, so I may be wrong :)

15 Aug
11 months ago

andonovn left a reply on Modifying Dates Returned By Query

@Cronix I agree that your solution is indeed the best (if there is such thing) approach to the problem. A "Laravel-ish" implementation of that would be to create a local Eloquent scope called something like scopeWithDatesInTimezone() so you can use it from the controller (and everywhere else) to make it look more nicely and human readable. Also, you can define that as a global scope if you want to apply it to all your queries. More about Eloquent scopes in the docs

@mr-gayda Just a ping so you can mark Cronix's reply as best one instead of mine. As that would help people in the future coming from Google to find the best approach faster.

14 Aug
11 months ago

andonovn left a reply on Modifying Dates Returned By Query

What you are doing is perfectly fine because it simply get the job done. I personally would do the same if that's something I need to achieve fast and if it's a small application where all it's doing is inside this controller.

That being said, here are few things you can consider if you still want to improve this:

  • I guess $results, $key and $value have these names for the sake of the example. But if that's really how you named the variables, then it would be cooler to name these better. In Laravel we value such small things.
  • Many folks would use the Collection instance you have (your $results variable) and will get rid of the foreach in favour of collection method called transform. That would also get rid of the temporary variable $results as it would be redundant.
  • If that's a bigger application, a good thing would be to clean your controller from that logic. The more "Laravel-ish" way of doing this is to create a custom request instance and move the transformation logic there. Then your controller could end up looking similar to just return $request->applyTransformers(Something::select('created_at', 'value')->get());
22 Jul
1 year ago

andonovn left a reply on Vue Like Component In Posts View

Not really sure I understood the question but you can have as many instances of a component as you want to on any page.

andonovn left a reply on Customizing Laravel Built-in Auth

Do you have a reason to have a separate accounts table? And, do you insist on first inserting the users' data into the accounts table?

If the answer to the both questions is "no", then you can achieve all that easily by merging all the columns into the users table, then use the build-in php artisan make:auth, and also create one middleware class to check for the is_approved flag.

Otherwise, you can just build the controllers manually which is pretty straight-forward if you ask me.

And of course another option would be to use the php artisan make:auth command, and then tweak both the RegisterController and LoginController controllers, where you can optionally override methods from the RegistersUsers and AuthenticatesUsesr traits respectively.

04 Jul
1 year ago

andonovn left a reply on Eloquent Resets Some Columns Stored As $dates To NOW()

I've just solved the same problem after spending an hour of pulling my hair out. It was all on the database layer. For some weird reason beyond my understanding if a timestamp column is not null, some databases will set a default value of CURRENT_TIMESTAMP and also will update your column to CURRENT_TIMESTAMP on every update. I really find this frustrating and stupid, but I am sure there is a good reason for this that I personally don't know about. So I end up adding ->nullable() to all my timestamp columns in all my migration files. Luckily, I am not in production yet and I could actually do that, but I will have to take a look at my past projects where things may be more tricky.

@chrisgeary92 I know it's been two years now and most probably you figured this out, but I am posting this for any potential developers who may have this weird issue in the future. Because I ended up in your topic after a search in Google. And I guess I won't be the last one who will search for this issue. So hopefully I saved someone else's time :)

andonovn left a reply on How To Validate Array Input Fields?

I've quickly write it directly here in the comment just for the illustration purposes. Tweak it a little bit and you will get it working. Or if you can't, let us know what's the error you can't tackle. "It's not working" is how an end user can describe the code. If you consider yourself a developer, or someone who wants to be one, try to figure out the problem and solve it. Or describe in details what have you tried so far and what makes you struggle. So others can guide you.

02 Jul
1 year ago

andonovn left a reply on How To Validate Array Input Fields?

You can use a form request class with php artisan make:request and use the withValidator() method to perform your custom validation. Which may look something like

protected function withValidator(Validator $validator) : void
{
    if (! is_array($request->name) || ! is_array($request->city) || ! is_array($request->address)) {
        return;
    }

    $validator->after(function (Validator $validator) {
        foreach ($request->name as $index => $name) {
            if (isset($name)) {
                if (! isset($request->city[$index])) {
                    $validator->errors()->add('city.' . $index, 'City is required');
                }
                if (! isset($request->address[$index])) {
                    $validator->errors()->add('address.' . $index, 'Address is required');
                }
            }
        }

        // repeat for city and address
    });
}

andonovn left a reply on How To Make That In Eloquent

  1. The spec model belongsTo product. And the inverse is the product hasMany specs.

  2. Then the bizProductSpec belongsTo to both bizProduct and spec. The inverse again is bizProduct hasMany bizProductSpec, and spec hasMany bizProductSpec. Alternatively, you can threat the bizProductSpec as a Pivot, thus defining a relationship of belongsToMany between the bizProduct and Spec models. So you can end up having the following in the both models:

// BizProduct.php
public function specs()
    return $this->belongsToMany(BizProduct::class)
        ->withPivot('value');
// Spec.php
public function bizProducts()
    return $this->belongsToMany(Spec::class)
        ->withPivot('value');

Just don't forget the withPivot('value'). And in the future if you add more columns in the bizProductSpec table you will need to specify them, too.

27 Jun
1 year ago

andonovn left a reply on Adding Payment Authentication

@markMngoma php artisan make:auth and you have the authentication

Then you need to create a middleware which will check if the user is subscribed and redirect to the subscription page if they are not.

For the subscription page itself you can use Laravel Cashier

For the terms and conditions you can just modify the RegisterController a bit, and of course the blade template.

The account verification at the moment you would need to build manually, but again is very straight forward. By the way, if I am not mistaken Taylor is working on this at the moment and that would be included in the php artisan make:auth in the next release of Laravel.

Hopefully all that makes sense? :)

11 Jun
1 year ago

andonovn left a reply on Problem With A Component Not Updating The DOM After Prop Has Changed

I believe you need to add an unique key on line 16 of the StockAllocationsForm. So you should end up with something like <tr v-for="(allocation, index) in allocations" :key="allocation.id">.

That's a good practice in Vue to avoid problems like the one you have. The initial problem occurs for performance reasons, Vue tries to replace the DOM as little as possible and cache everything possible. Giving an unique key for each item when using v-for is how you instruct Vue which item is which when it is re-rendering the list. Hopefully that makes sense.

01 Jun
1 year ago

andonovn left a reply on Best Way To Handle Complex Form With Laravel Vs Vue

@hepabolu As with almost any other thing, there is no such thing as best approach. You can tackle that either with or without javascript so it's all up to you. Having said that, here is how I would tackle this:

  1. Obviously create a route and attach a controller to handle it. Probably I would name it BookController and will use a create method to display the form. Just to stick with the default Laravel conventions. But keep in mind that's optional.
  2. In the create.blade.php file I would make use of a Vue component which will handle the form.
  3. Inside that component, I would have a property called most probablystatus which by default would be something like waiting-for-isbn. Based on that variable, I would show the ISBN field only.
  4. When the user types the ISBN (and hit the Next button?) I will hit the backend via AJAX. There I would check if I have a book with that ISBN stored, and if so will return 422. Otherwise, I will fetch from the 3rd party provider. If the fetch fails, I will return 404, otherwise 200 with the information I got.
  5. Back on the client I can just check the status code and update my status variable. And of course I will bind different things in my template to that status variable. So I can show/hide different responses to the user. For example, if the response is 200, then obviously I am displaying the rest of the fields prepopulated with what I got from the 3rd party source. If the response is 422, I am displaying an error message that we already have that book. For 404 maybe just making the ISBN input border red with hint to change it or look for typo. You got the idea.
  6. Then when the user submit the form I will have a store method inside my BookController where I will just store the book. And of course validate the user's field, alongside the ISBN again, prior to storing.

For the author "fuzzy matching" you can use Laravel Scout which is a full-text search and by default ships with Algolia. Once you have the suggestions, it's very simple to show these to the user and let him pick one (again, you will just bind the user's choice to a variable in the Vue component)

Hopefully all that makes sense? Let me know if something is not clear and I will go in more details :)

23 May
1 year ago

andonovn left a reply on Selecting Laravel Version

@Nagamma As with almost any other software, you should go with the latest version of the framework. That way, you will have as much as possible bugs fixed, long-term support, security updates, and most importantly cool new features.

20 May
1 year ago

andonovn left a reply on $app['config']

@Mahmoudy Most probably the $app variable is holding an instance of the Illuminate\Foundation\Application

When you access it as array, it will resolve from the service container. Since the 'config' is automatically bind to Illuminate\Config\Repository you receive an instance of that object.

And when you access that object as array, it will look in your config directory and will return you the values from there. So $app['config']['session'] will return the whole content of the config/session.php file. While $app['config']['session.lifetime'] will look at the same file but will return you only what you have stored under the lifetime key.

You can use php artisan tinker and play around with things like this. And you will be able to explain by yourself when you have such doubts in the future. To access the $app variable there, you can just use the app() helper. So just start by $app = app();

09 May
1 year ago

andonovn left a reply on Ignores My Middleware In Controller, Why?

@shadrix By default, phpunit is not ignoring the middlewares, just tested this using Laravel 5.6. So it should be something on your side. What's the source of the signIn() method? Maybe for some reason it is calling $this->withoutMiddleware(); which instructs is disabling the middlewares.

Also, are you running phpunit with the filter option set to a_confirmed_auth_user_cannot_see_the_resend_page?

08 Jan
1 year ago

andonovn left a reply on User (client) Accounts & Sub Accounts?

@alturic What exactly are you afraid of? If you can build the appropriate database schema, then do it. Laravel won't put any limitations on that. It will help you to query it easily if you decide to use Eloquent.

From Auth point of view, you can use the default Authentication php artisan make:auth and override what you are not okay with. And of course you are free to not use the default Auth at all, and build one from scratch for your needs.

andonovn left a reply on Multi Tenancy On SPA

@brigman Just use your database? When a user changes the company, you should hit an endpoint to update that in your database. For all the other requests you just read the logged in user's selected company from the database and serve the appropriate data.

If that's all you need, you can even use Redis instead of database to speed up the reading.

20 Dec
1 year ago

andonovn left a reply on Is There Any Substitute Method In Laravel For Before() And After() Methods Of Kohana?

@khurram11 Not sure what's your use-case but maybe what you are searching for is called a "Middleware" in Laravel. You can hook some things before and/or after the request. More information and usage in the docs

Maybe if you share what exactly you want to achieve, I or someone else will be able to help you more.

16 Dec
1 year ago

andonovn left a reply on Best Practice For Generate Laravel Request Validation In Rest Api App

@vahidvs I don't think this is actually a problem. Having lots of Request classes is okay. If you are repeating yourself in some of them, just extract the shared code in a parent abstract class.

12 Dec
1 year ago

andonovn left a reply on Sending A Form-data Post Request With Guzzle Http

$http = new GuzzleHttp\Client;

$response = $http->post('https://your-endpoint.com', [
    'form_params' => [
         // data goes here
    ],
]);

andonovn left a reply on Many To Many Page Followers Efficiency?

@AR Well, I didn't know if you have reasons to do this, that's why I used the word usually :)

Thumbs up for having only CRUD methods in your controllers.

andonovn left a reply on Many To Many Page Followers Efficiency?

@ar From what I am seeing, it looks good to me. However, the more natural approach would be without the PageFollower model. Usually, pivot tables are not represented as Eloquent models. Then both your followings() and followers() methods would have belongsToMany instead of hasManyrelationships.

03 Dec
1 year ago

andonovn left a reply on Request Validation From Custom Table.

@VigoKrumins How about 'email' => 'required|unique:' . (new User)->getTable() ?

26 Nov
1 year ago
25 Nov
1 year ago

andonovn left a reply on How To Manage Migration Of Db Content With Existing Data?

@resting Why not writing that logic in a migration file?

andonovn left a reply on Optimize Static Page Routes And Views

@bnazarov@abv.bg I've just read this article which perfectly apply to your case: https://laravel-news.com/viewfirst

23 Nov
1 year ago

andonovn left a reply on How To Push A Component Onto List Of Dynamic Components

@benjackson Maybe like this:

let item = {
    id: 'the-new-component-id',
    type: 'the-new-component-name',
    // your other item data
};

this.feed.push(item);

andonovn left a reply on Scope Problem In User Model

@NightM4re What are your imports (the use statements at the top) in the VentaController.php?

And make sure to return the query builder from your scopeNombre method.

andonovn left a reply on Scope Problem In User Model

What are your imports (the use statements at the top) in the VentaController.php?

And make sure to return the query builder from your scopeNombre method.

20 Nov
1 year ago

andonovn left a reply on Optimize Static Page Routes And Views

@bnazarov@abv.bg I think you are in the right direction in regards to the "view exists" solution. Here is how it may look:

Route::get('page/{slug}', '[email protected]'); in your routes file web.php or routes.php (depending on the Laravel version)

public function show()
{
    $template = 'pages/' . request('slug');

    if (! view()->exists($template) {
        abort(404);
    }

    return view($template);
}

^ that's of course the PageController.php

If you don't want your URL to match your view filenames, then you can add one array to map the differences. But the logic stays the same.

Another solution would be to make the pages dynamic (ie to store them in database) which would allow site administrators to add/change them, and again reduce all your methods to one single show method. But you would need to hit the database with that approach.

09 Nov
1 year ago

andonovn left a reply on Filtering With A Dynamic Key Problems

@jgravois What's the exact error? Also, turn the Vue dev tools on (I am aware of the Chrome extension only but there might be others, too) and see if all of the data and props' values are exactly what you are expecting these to be. An alternative would be to add console.log(this.typer) as well as few more for each of the variables.

andonovn left a reply on Call To A Member Function GetUpdatedTemplate() On Null

@muazzamazaz Most probably you are receiving the error on this line $template->getUpdatedTemplate($template, $request); which is part of the Save_Template() method. That's because few lines above $template = Notification_Template::find($request->id); is returning null. Most probably you didn't pass the id parameter correctly or you don't have an existing template with that id in the database.

06 Nov
1 year ago

andonovn left a reply on Testing Updates With Live Data

@livijn If you are using MySQL, you have the mysqldump command which can export the db, or parts of the db. Examples to export the production db and examples to import locally. You don't have to write a script for this :) And I believe different databases (other than MySQL) would have a similar build-in feature.

05 Nov
1 year ago

andonovn left a reply on Find Results For Specified User If They Exists

@nenads Then the only thing in my mind is to manually write the query. Something like this (not tested tho)

$tests = Test::leftJoin('test_user', 'test_user.test_id', '=', 'tests.id')
    ->leftJoin('users', 'test_user.user_id', '=', 'users.id')
    ->where(function ($query) {
        $query->where('users.id', '=', $user->id)
                    ->orWhereRaw('users.id IS NULL');
    });

I don't really like the @robrogers3 suggestion as there would be one hell of methods to define the same relationships for different use-cases. It's more straight-forward to have the relationships defined in one place only, and use them per your needs.