Niush

Member Since 8 Months Ago

Nepal

Experience Points
17,910
Total
Experience

2,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
125
Lessons
Completed
Best Reply Awards
8
Best Reply
Awards
  • start your 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-in-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 Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist 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 4
17,910 XP
Oct
25
1 day ago
Activity icon

Replied to How Can We Protect Uploaded Images And Pdf Files In Laravel

My suggested approach.

For Publicly viewable Files Store it with 'public' filesystem disk.

if(request()->hasFile('image') && request()->file('image')->isValid()){
     $post->image = request('image')->store('post', 'public');
}

So if you visit myurl/storage/post/filename.jpeg it is visible. To get url Storage::url(Post::first()->image)

For Private files store without 'public' filesystem disk or 'local' by default.

if(request()->hasFile('image') && request()->file('image')->isValid()){
     $post->image = request('image')->store(auth()->user()->id.'/post');
}

The path is myurl/user_id/post/filename.jpeg. But this path is not served from public so is hidden.

Then, finally to access the file create a route in web.php that takes the image url as param.

// Where url can be generated with Storage::url(Post::first()->image)
Route::get('storage/{url}', function ($url) {
    $user_id = request()->segments()[1] ?? null; // get user_id from url
    if (!$user_id || !Storage::exists($url) || $user_id != auth()->user()->id){
       abort('404');
    }
    $path = storage_path('app' . DIRECTORY_SEPARATOR . $url);
    return response()->file($path);
})->where(['url' => '.*']);

Note: If you use AWS S3 then look into File Visibility. https://laravel.com/docs/8.x/filesystem#file-visibility

Oct
13
1 week ago
Activity icon

Replied to How Pass Param Route If The Param Is On JS File

If you are using Ajax or Axios, you could do something like:

$.ajax({
        url: "/generate/pdf",
        type: "post",
        data: {
		"id": [1,2,3,4]
	},
        success: function(res) {
            console.log(res);
        }
});

Or, If you are using normal Form Request:

In a hidden input field set value to array of ids.

<input type="hidden" value="[1,2,3,4]" name="id"/>

Then, in the Laravel decode it as:

$ids = json_decode(request('id'));
Activity icon

Replied to The Profile Picture In Jetstream Dashboar

In your config/jetstream.php, uncomment Features::profilePhotos().

In the initial release of Laravel Jetstream this was enabled by default. But, now according to community recommendation this has been disabled by default. Just uncomment this to enable it.

Oct
10
2 weeks ago
Activity icon

Replied to TEMPORARY Table In Laravel

Hey, @araw for what you are trying to do, using Laravel Cache might be a good idea. https://laravel.com/docs/8.x/cache

use Illuminate\Support\Facades\Cache;

Cache::add('msg:2:3', 'message temp check', now()->addMinutes(10));
$data = Cache::get('msg:2:3');
Cache::forget('msg:2:3');
Oct
09
2 weeks ago
Activity icon

Replied to How To Append Multiple Imagein FormData?

That look fine and should be working. Make sure there are not any extra /addproject elsewhere with GET method. Otherwise it looks good. May be a php artisan cache:clear and php artisan route:clear might help.

Activity icon

Replied to How To Append Multiple Imagein FormData?

First File Input Field can have multiple attribute. So, that user can select multiple files.

<input type="file" id="files" name="files[]" accept="image/*" multiple/>

Then, Form Data append would be something like this.

let formData = new FormData();
let files = $('#files').prop('files');
for(let i = 0 ; i < files.length ; i++){
	formData.append('files[]', files[i]);
}

Then, Laravel Backend would be:

request()->validate([
        'files.*' => 'mimes:jpeg,png,jpg,gif,svg',
]);
// Laravel/PHP will automatically create list of request with [] in it

if(request()->has('files')){
        foreach (request()->file('files') as $file) {
            $name = (string) Str::uuid() . '.' . $file->extension();
            $file->storeAs('upload', $name);
        }
}
Oct
02
3 weeks ago
Activity icon

Replied to Pivot Table With Only Created_at Timestamp

This can be alternative and simple solution. (Observer might seem overkill)

class PostTag extends Model 
{

    public static function boot()
    {
        parent::boot();

        static::creating(function($model){
            $model->setCreatedAt($model->freshTimestamp());
        });
   }
}

with $table->dateTime('created_at'); in migration.

Activity icon

Replied to Nested Checkboxes Vue

You can utilize Vue.js Recursive Components logic to create infinitely nested Checkbox Components. And Show/Hide components checking parent checked status. https://vuejs.org/v2/guide/components-edge-cases.html#Recursive-Components

Then, you can @change event on checkbox to add/remove checked item to Array List.

Activity icon

Replied to How To Detect Enter Key In Vue?

@keyup.enter="search" should work fine. It will only trigger when Enter key is pressed.

Sep
29
3 weeks ago
Activity icon

Replied to JetStream: Change NameSpace Model User,Team,Member

After you have changed the Namespace of User.php by moving it into Authentication Folder like this namespace App\Models\Authentication;

Then you also need to change config/auth.php providers key. (Or use database driver commented)

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\Authentication\User::class,
    ],
],

Combine this with Jetstream Solution from your Github Issue.

Sep
27
4 weeks ago
Activity icon

Replied to New Template Inertia Vue

Probably you should first look into Basics of Vue.js and Inertia before trying them out.

You need to add the page vue component in \resources\js\Pages\UpdateSocialForm.vue and return with this name correctly from Laravel Backend.

Sep
23
1 month ago
Activity icon

Replied to Anonymous Users After Deleting Account

You might be overwhelmed by multiple approach suggested here. All approach are good, test for yourself and find the suitable one.

Here is my approach. Using default models in the relation itself.

https://laravel.com/docs/8.x/eloquent-relationships#default-models

Example: In the User relation inside of Comment/Post Models

/**
 * Get the author of the post.
 */
public function user()
{
    return $this->belongsTo('App\Models\User')->withDefault(function ($user, $post) {
        $user->name = 'Anonymous User';
	$user->id = 0; // Check if id is falsy (to disable link to user profile etc.)
    });
}

And in migration on user foreign key ->onDelete('set null')

Sep
18
1 month ago
Activity icon

Awarded Best Reply on How Reduce Size Of App.js And Vendor.js Or How To Split Vendor To Different Chunks

Yes, try to import as less components and modules as possible. Look through all packages. It can surely lower the size.

Also, look through Vue Router Lazy Loading, it can be helpful. https://router.vuejs.org/guide/advanced/lazy-loading.html

https://laravel-news.com/using-dynamic-imports-with-laravel-mix

Sep
16
1 month ago
Activity icon

Replied to How To Style My Notifications

You need to keep your custom css file ck.css in html/themes directory inside views. Laravel is not going to check into every other folders inside views.

resources/views/html/themes/ck.css

Activity icon

Replied to How Reduce Size Of App.js And Vendor.js Or How To Split Vendor To Different Chunks

Yes, try to import as less components and modules as possible. Look through all packages. It can surely lower the size.

Also, look through Vue Router Lazy Loading, it can be helpful. https://router.vuejs.org/guide/advanced/lazy-loading.html

https://laravel-news.com/using-dynamic-imports-with-laravel-mix

Sep
15
1 month ago
Activity icon

Awarded Best Reply on Jetstream - Is It Possible To Publish VerifyEmail

I don't think this is changed in Laravel 8. Just like before you should be able to send custom Verification Email by using this inside boot function of AppServiceProvider.

<?php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Notifications\Messages\MailMessage;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        VerifyEmail::toMailUsing(function ($notifiable,$url){
            $mail = new MailMessage;
            $mail->subject('Welcome!');
            $mail->markdown('emails.verify-email', ['url' => $url]);
            return $mail;
        });
    }

    public function register()
    {
        //
    }
}

Or if you want to publish the Notification views use this:

php artisan vendor:publish --tag=laravel-notifications

And for publishing laravel-mail blade components and theme use this:

php artisan vendor:publish --tag=laravel-mail

Activity icon

Replied to How Reduce Size Of App.js And Vendor.js Or How To Split Vendor To Different Chunks

Make sure you are importing only required Modules. For example in case of vue2-leaflet use:

import { LMap, LTileLayer, LMarker } from 'vue2-leaflet';

https://github.com/vue-leaflet/Vue2Leaflet#importing-the-library-in-webpack--rollup

And similar approach for other possible large packages. Even v-calendar & moment are pretty heavy.

Check here: https://bundlephobia.com/

Activity icon

Replied to Logic Exception

In the api.php the route for api/user is probably handled in Closure (Instead of Controller)

So, the artisan command php artisan route:cache cannot serialize the closure

Since this feature uses PHP serialization, you may only cache the routes for applications that exclusively use controller based routes. PHP is not able to serialize Closures. https://laravel.com/docs/7.x/deployment#optimizing-route-loading

Now, when running migration this should not be occurring unless route:cache is ran. Probably an alias command was created?

This might be fixed in Laravel 8 (Not Sure though)

@sinnbeck Is it fixed in Laravel 8 ? Any idea. The new documentation does not include this warning.

Activity icon

Replied to Jetstream - Is It Possible To Publish VerifyEmail

I don't think this is changed in Laravel 8. Just like before you should be able to send custom Verification Email by using this inside boot function of AppServiceProvider.

<?php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Notifications\Messages\MailMessage;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        VerifyEmail::toMailUsing(function ($notifiable,$url){
            $mail = new MailMessage;
            $mail->subject('Welcome!');
            $mail->markdown('emails.verify-email', ['url' => $url]);
            return $mail;
        });
    }

    public function register()
    {
        //
    }
}

Or if you want to publish the Notification views use this:

php artisan vendor:publish --tag=laravel-notifications

And for publishing laravel-mail blade components and theme use this:

php artisan vendor:publish --tag=laravel-mail

Sep
14
1 month ago
Activity icon

Replied to Lumen Or Laravel For API Development?

Lumen is basically Laravel cut off with lots of features to make it lighter. Development probably will not be stopped any time soon.

The main thing to know before choosing Lumen: Is it enough for your app? Will your app grow in the future? Might you need rendering views?

There are lots of features like Route Model binding that does not exists in Lumen. If your application is very simple, and you know for certain that the possibility of it growing (and feature adding) is not higher, then you can use Lumen.

Sep
13
1 month ago
Activity icon

Replied to Version 8 Redirects

Yes, can confirm to @assoft

There is no Contracts\TwoFactorLoginResponse thingy to bind with custom Response. (There is one for TwoFactorChallengeViewResponse only.)

So, when user login successfully, then when 2fa is enabled, laravel will not use LoginViewResponse.

The \Laravel\Fortify\src\Http\Responses\TwoFactorLoginResponse.php is where fortify redirects to dashboard. Now, this cannot be used to bind like contracts.

Activity icon

Replied to Laravel 8: RedirectTo() Customize (Login Controller Kinda)

@jlrdw Yes, it works. The solution looks like sort of workaround. But, I guess that is how it is now.

Solution:

In JetstreamServiceProvider.php, inside boot function, we can bind Fortify Response to our own files.

  • JetstreamServiceProvider.php
public function boot()
    {
        $this->configurePermissions();

        Jetstream::deleteUsersUsing(DeleteUser::class);

        // CUSTOM LOGIN RESPONSE //
        $this->app->singleton(
            \Laravel\Fortify\Contracts\LoginResponse::class,
            \App\Http\Responses\LoginResponse::class
        );

        // CUSTOM LOGIN VIEW PAGE //
        $this->app->singleton(
            \Laravel\Fortify\Contracts\LoginViewResponse::class,
            \App\Http\Responses\LoginViewResponse::class // returns custom login blade
        );
    }
  • app\Http\Responses\LoginResponse.php
<?php

namespace App\Http\Responses;

use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;

class LoginResponse implements LoginResponseContract
{

    public function toResponse($request)
    {
        if (Session::has('next')) {
           return redirect(Session::get('next'));
        }elseif (request('next', false)){
           return redirect(request('next'));
        }
        
        return $request->wantsJson()
                    ? response()->json(['two_factor' => false])
                    : redirect()->intended(config('fortify.home'));
    }

}
Activity icon

Replied to Laravel 7 Vs Laravel 8 Dilemma

Any suggestions or work around idea for this:

Laravel 8: redirectTo() Customize (Login Controller kinda) - https://laracasts.com/discuss/channels/laravel/laravel-8-redirectto-customize-login-controller-kinda

Activity icon

Started a new Conversation Laravel 8: RedirectTo() Customize (Login Controller Kinda)

In Laravel 7, there was LoginController where we could override the redirectTo() function, e.g.

public function redirectTo(){
    if (Session::has('next')) {
        $this->redirectTo = Session::get('next');
    }elseif (request('next', false)){
        $this->redirectTo = request('next');
    }
    return $this->redirectTo ?? RouteServiceProvider::HOME;
}

As, well as we could override credentials() function & showRegistrationForm in Register Controller.

Is there similar option in Laravel 8 ? (Some sort of Login/Register Controller + Other)

Are we stuck with JetStream implementation or Own Manual (Bad) Code ?

(May be a vendor:publish option for publishing such Controllers???)

Sep
12
1 month ago
Activity icon

Replied to Notification Data Empty

You can always use php artisan queue:listen while on development.

This will automatically restart the worker when code change is detected. (Not intended for use in Production)

Activity icon

Awarded Best Reply on Why Does This Not Work?

In first case $bill will be e.g. ["id" => 1, "customer_id" => 1]. Here, customer relation can be accessed for this specific bill instance.

In Second case, $bill will be array of multiple bill instance i.e. [Bill1, Bill2] etc. You cannot directly access customer relation from array (But, it could be for Bill1->customer)

The Solution:

1 - Either, loop through $bill in second case, like

foreach(Bill::all() as $bill){
	return $bill->customer; // Here, query is ran for each bill customer relation
}

2 - Or, you could use eager loading. Which utilizes join sql query, like

$bills = Bill::all()->with('customer');
foreach(Bill::all() as $bill){
	return $bill->customer; // Here query is not ran again
}
Activity icon

Replied to Why Does This Not Work?

In first case $bill will be e.g. ["id" => 1, "customer_id" => 1]. Here, customer relation can be accessed for this specific bill instance.

In Second case, $bill will be array of multiple bill instance i.e. [Bill1, Bill2] etc. You cannot directly access customer relation from array (But, it could be for Bill1->customer)

The Solution:

1 - Either, loop through $bill in second case, like

foreach(Bill::all() as $bill){
	return $bill->customer; // Here, query is ran for each bill customer relation
}

2 - Or, you could use eager loading. Which utilizes join sql query, like

$bills = Bill::all()->with('customer');
foreach(Bill::all() as $bill){
	return $bill->customer; // Here query is not ran again
}
Sep
11
1 month ago
Activity icon

Awarded Best Reply on What (MySQL) Data Type For Saving E-mail HTML Content?

Normally I use mediumText for HTML and WYSIWYG content. It is about ~16MB and should be enough.

But, if storage space matters, and content is about ~60kb then text is also enough.

Activity icon

Replied to What (MySQL) Data Type For Saving E-mail HTML Content?

Normally I use mediumText for HTML and WYSIWYG content. It is about ~16MB and should be enough.

But, if storage space matters, and content is about ~60kb then text is also enough.

Activity icon

Awarded Best Reply on It's Possible To Pass The Route That The User Is Accessing To Use In The Middleware?

Is this what you are looking for?

return request()->route()->uri();
// or
// return request()->route()->getName();
Activity icon

Replied to It's Possible To Pass The Route That The User Is Accessing To Use In The Middleware?

Is this what you are looking for?

return request()->route()->uri();
// or
// return request()->route()->getName();
Aug
15
2 months ago
Activity icon

Awarded Best Reply on Pre-selecting Values With Select2

Something like this:

<select .....>
	@foreach ($subcategories as $subcategory)
		<option value="{{ $subcategory->id }}">{{ $subcategory->name }}<option>
	@endforeach
	<option value="{{ $requirement->source->id }}" selected>{{ $requirement->source->name }}<option>
</select>
Activity icon

Replied to Pre-selecting Values With Select2

Something like this:

<select .....>
	@foreach ($subcategories as $subcategory)
		<option value="{{ $subcategory->id }}">{{ $subcategory->name }}<option>
	@endforeach
	<option value="{{ $requirement->source->id }}" selected>{{ $requirement->source->name }}<option>
</select>
Activity icon

Awarded Best Reply on Issue: Sanctum API Test With Postman (SPA / Same Domain)

It is certainly a problem with Postman Desktop app itself. (With certain versions)

For anyone with this problem, the simplest and temporary solution would be to change this vendor file: /vendor/laravel/sanctum/src/Http/Controllers/CsrfCookieController.php

and return response with status code 200 (instead of 204) in the show function.

public function show()
{
    return new Response('', 200);
}

EDIT:

Seems, to be problem with how Laravel (Symfony) sends 204 response. Testing with other 204 response (Nodejs) seems to be working. My Issue at postmanlabs.

Similar issue raised at Symfony here: https://github.com/symfony/symfony/issues/29326

Activity icon

Replied to Issue: Sanctum API Test With Postman (SPA / Same Domain)

It is certainly a problem with Postman Desktop app itself. (With certain versions)

For anyone with this problem, the simplest and temporary solution would be to change this vendor file: /vendor/laravel/sanctum/src/Http/Controllers/CsrfCookieController.php

and return response with status code 200 (instead of 204) in the show function.

public function show()
{
    return new Response('', 200);
}

EDIT:

Seems, to be problem with how Laravel (Symfony) sends 204 response. Testing with other 204 response (Nodejs) seems to be working. My Issue at postmanlabs.

Similar issue raised at Symfony here: https://github.com/symfony/symfony/issues/29326

Aug
14
2 months ago
Activity icon

Started a new Conversation Issue: Sanctum API Test With Postman (SPA / Same Domain)

Testing Laravel Sanctum api with Postman is not working.

I am using the following tutorial which uses Postman pre-request scripts to make call to /sanctum/csrf-cookie

https://codecourse.com/courses/laravel-sanctum-airlock-with-postman

pm.sendRequest({
    url: pm.environment.get('base_web_url')+'/sanctum/csrf-cookie',
    method: 'GET'
}, function (error, response, { cookies }) {
    if (!error && cookies) {
        pm.environment.set('xsrf-token', cookies.get('XSRF-TOKEN'))
        pm.request.headers.add({key: 'X-XSRF-TOKEN', value: cookies.get('XSRF-TOKEN') })
    }
})

But, Postman throws Error: Parse Error: Expected HTTP/ because sanctum returns 204 header, and postman cannot parse (or idk ignores) the cookie.

Is there any other and better way to test Sanctum API (Same Domain) in Postman?

Note: It is kind of a postman bug, because it was working fine in previous versions. But, it seems to be a old and recurring problem in postman.

Cannot Sanctum return a 200 response so that this issue is solved.

Jul
04
3 months ago
Activity icon

Replied to Mix With Vuetify

Any solutions for testing vue with Mochapack? It keeps failing while compiling showing the errors to be in the sass/scss of vuetify.

Run dev, prod all are fine. The testing seems to be broken by vuetify.

Jul
02
3 months ago
Activity icon

Replied to Autorefresh Div

As per your requirements, probably it is good to look into https://laravel-livewire.com/

It is realtime with only blade (no vue/socket).

Jun
21
4 months ago
Activity icon

Replied to Laravel 7 Single Image Store Instead Of Multiple Images.

Many factors might be affecting here.

  • Business model is storing url of single image only, with just one image column
  • date('YmdHis') is used to name multiple files inside foreach loop so that the filename are overridden.

You, should use (string) \Str::uuid() to generate unique name.

$fileName = (string) \Str::uuid() . "." . $file->getClientOriginalExtension();
Activity icon

Awarded Best Reply on Broadcasting To Guests

Source Code would be helpful to understand. The core concept is Private and Presence Channel needs authorization while Channel is equivalent to Public which does not require authorization.

public function broadcastOn()
{
    return new Channel('survey.'.$this->id);
}
Jun
20
4 months ago
Activity icon

Replied to Broadcasting To Guests

Source Code would be helpful to understand. The core concept is Private and Presence Channel needs authorization while Channel is equivalent to Public which does not require authorization.

public function broadcastOn()
{
    return new Channel('survey.'.$this->id);
}
Jun
18
4 months ago
Activity icon

Replied to Recommended Package For Dynamic Tenancy In Laravel 6

stancl/tenancy is the only package I have used and renaming database is possible. While creating new tenant you can specify it.

Tenant::create([
    'tenancy_db_name' => 'testdb',
    'tenancy_db_username' => 'admin',
    'tenancy_db_password' => 'password',
]);
Jun
17
4 months ago
Activity icon

Awarded Best Reply on I Need Help Removing Unused Javascript

mix.js('resources/js/app.js', 'public/js')
    .extract()

Can also be used to split the packages into app, vendor, manifest.

And, I believe Laravel Mix does tree shaking in npm run prod only.

Jun
15
4 months ago
Activity icon

Replied to Validate Count Max Value With Text Include Break Line (new Line)

Line Break, Space, Tabs all are counted in validation as a character. Database will also count that as a character.

And, so does JavaScript. What, validation are you using in JavaScript? Make sure that front-end validator is counting these as a character instead.

Jun
14
4 months ago
Activity icon

Replied to I Need Help Removing Unused Javascript

mix.js('resources/js/app.js', 'public/js')
    .extract()

Can also be used to split the packages into app, vendor, manifest.

And, I believe Laravel Mix does tree shaking in npm run prod only.

Activity icon

Replied to Conditional Views

It is good enough. But to make it even better you could:

  • Create isAdmin() and isEmployee() model function
  • Use === instead
  • And write abort outside else to make it cleaner
// Controller

public function index() {
        if (auth()->user()->isAdmin()) {
            return view('dashboard.admin');
        }elseif (auth()->user()->isEmployee()) {
            return view('dashboard.employee');
        }

	abort(403);
}


// User Model
// ...

public function isAdmin(){
	return $this->role === 'Admin';
}

public function isEmployee(){
	return $this->role === 'Employee';
}

// ...
Jun
12
4 months ago
Activity icon

Replied to Sanctum Custom Middleware

For that as hinted above you need to implement this function inside App\Exceptions\Handler.php

    /**
     * Convert an authentication exception into a response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Auth\AuthenticationException  $exception
     * @return \Symfony\Component\HttpFoundation\Response
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {

	// Here you can return your own response or work with request
	// return response()->json(['status' : false], 401);

	// This is the default
        return $request->expectsJson()
                    ? response()->json(['message' => $exception->getMessage()], 401)
                    : redirect()->guest($exception->redirectTo() ?? route('index'));
    }
``
Jun
11
4 months ago
Activity icon

Replied to Sanctum Custom Middleware

Laravel will return a view if the request has no Accept or Content-Type Header.

But, if you include any one of these header ( NOT BOTH ) when requesting, Laravel will return respective error as json.

Mostly, Accept: application/json is common.

This is the Code that Laravel uses to determine the request type in case of unauthenticated:

protected function unauthenticated($request, AuthenticationException $exception)
    {
        return $request->expectsJson()
                    ? response()->json(['message' => $exception->getMessage()], 401)
                    : redirect()->guest($exception->redirectTo() ?? route('index'));
    }