tanmay_das

tanmay_das

Member Since 2 Years Ago

Chittagong

Experience Points 17,940
Experience Level 4

2,060 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 129
Lessons
Completed
Best Reply Awards 3
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.

17 Jun
1 month ago

tanmay_das started a new conversation Cannot Resolve Dependency In A Job Dispatched From An Artisan Command's Handle Method

I have a custom artisan command. I am trying to dispatch a job from its handle() method. The job has a dependency. The dependency is resolved when I normally use the app, but it's failing to resolve when I run the command from the console:

Symfony\Component\Debug\Exception\FatalThrowableError(code: 0): Cannot instantiate interface App\Services\ABCInterface at /Users/john/code/laravel-project/app/Providers/ABCServiceProvider.php:28)

Why is this happening?

18 Apr
3 months ago

tanmay_das left a reply on Laravel Event Is Not Broadcasting On Production Server

For anyone having the same issue:

I changed host to the production URL:

Here is the updated config:

'pusher' => [
    'driver' => 'pusher',
    'key' => env('PUSHER_APP_KEY'),
    'secret' => env('PUSHER_APP_SECRET'),
    'app_id' => env('PUSHER_APP_ID'),
    'options' => [
        'cluster' => env('PUSHER_APP_CLUSTER'),
        'encrypted' => true,
        'host' => env('PUSHER_HOST'),
        'port' => 6001,
        'scheme' => env('PUSHER_SCHEME')
    ],
],

And in the .env file:

PUSHER_HOST=example.com

Remember to exclude http/https from the host. It's not https://example.com, it's example.com.

tanmay_das left a reply on Laravel Event Is Not Broadcasting On Production Server

What's interesting is that the Presence channel is working. Presence channel is not bound by the ssl constraints?

tanmay_das left a reply on Laravel Event Is Not Broadcasting On Production Server

Yes I also think that it has something to do with the SSL. Here is my updated pusher config:

    'pusher' => [
        'driver' => 'pusher',
        'key' => env('PUSHER_APP_KEY'),
        'secret' => env('PUSHER_APP_SECRET'),
        'app_id' => env('PUSHER_APP_ID'),
        'options' => [
            'cluster' => env('PUSHER_APP_CLUSTER'),
            'encrypted' => true,
            'host' => '127.0.0.1',
            'port' => 6001,
            'scheme' => env('PUSHER_SCHEME'),
            'curl_options' => [
                CURLOPT_SSL_VERIFYHOST => 0,
                CURLOPT_SSL_VERIFYPEER => 0,
            ],
        ],

I am also referencing local_cert and local_pk from my .env file like this:

 'local_cert' => env('LOCAL_CERT', null),

 'local_pk' => env('LOCAL_PK', null),

In .env:

LOCAL_CERT=/etc/nginx/ssl/mydomain.com/123456/server.crt LOCAL_PK=/etc/nginx/ssl/mydomain.com/123456/server.key

tanmay_das started a new conversation Laravel Event Is Not Broadcasting On Production Server

I am using laravel-websockets package for some real-time features. I am using redis as queue connection. I have an event TestUpdated which I am broadcasting on test.{id} private channel. The event gets fired and caught by the client properly when I am on a local machine. But on production server, I get BroadcastException thrown:

Illuminate\Broadcasting\BroadcastException in /home/forge/mydomain.com/vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/PusherBroadcaster.php:117

Horizon dashboard also exposes the event data:

{
event: {
test: {
class: "App\Test",
id: 1,
relations: [
],
connection: "mysql"
},
socket: null
},
connection: null,
queue: null,
chainConnection: null,
chainQueue: null,
delay: null,
chained: [
]
}

Fragment of my websockets.php config file:

'apps' => [
    [
        'id' => env('PUSHER_APP_ID'),
        'name' => env('APP_NAME'),
        'key' => env('PUSHER_APP_KEY'),
        'secret' => env('PUSHER_APP_SECRET'),
        'enable_client_messages' => true,
        'enable_statistics' => false,
    ],
],

My observations:

  • Pusher gets connected. authEndpoint hits properly. I
  • Presence channel works.
  • The noticable difference between local machine and production is that on production the scheme is https

I am using an arbitrary pusher app id, key and secret (someId, someKey and someSecret'). My client-side config:

window.Echo = new Echo({
    authEndpoint: 'my/endpoint',
    broadcaster: 'pusher',
    key: 'someKey',
    wsHost: process.env.NODE_ENV == 'development' ? window.location.hostname : 'mydomain.com',
    wsPort: 6001,
    wssPort: 6001,
    disableStats: true,
    encrypted: process.env.NODE_ENV == 'development' ? false : true
});

Config from broadcasting.php:

'pusher' => [
        'driver' => 'pusher',
        'key' => env('PUSHER_APP_KEY'),
        'secret' => env('PUSHER_APP_SECRET'),
        'app_id' => env('PUSHER_APP_ID'),
        'options' => [
            'cluster' => env('PUSHER_APP_CLUSTER'),
            'encrypted' => true,
            'host' => '127.0.0.1',
            'port' => 6001,
            'scheme' => env('PUSHER_SCHEME')
        ],
    ],

How do I fix this?

tanmay_das started a new conversation Laravel Notification Is Broadcasted When The Queue Connection Is Set To Database, But Not When Set To Redis

I am facing this weird issue, I have a notification App\Notifications\SomethingHappened.

I am using laravel-websockets package. I have my queue connection set to database and my notification class which implements ShouldQueue interface, has the following to* methods: toArray(), toMail() and another custom channel.

Also, the via() method has these channels: database, broadcast and conditionally (if the user has email), mail.

My broadcast route in channels.php looks like this:

Broadcast::channel('App.User.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

I do not have a toBroadcast() method since the documentation suggested that,

The toArray method is also used by the broadcast channel to determine which data to broadcast to your JavaScript client.

When I have my queue connection set to database, the notification is broadcasted to the client properly. Here is the log:

[2019-04-18 09:29:42][1] Processing: App\Notifications\SomethingHappened
[2019-04-18 09:29:46][1] Processed:  App\Notifications\SomethingHappened
[2019-04-18 09:29:46][2] Processing: App\Notifications\SomethingHappened
[2019-04-18 09:29:47][2] Processed:  App\Notifications\SomethingHappened
[2019-04-18 09:29:47][3] Processing: App\Notifications\SomethingHappened
[2019-04-18 09:29:47][3] Processed:  App\Notifications\SomethingHappened
[2019-04-18 09:29:47][4] Processing: App\Notifications\SomethingHappened
[2019-04-18 09:29:47][4] Processed:  App\Notifications\SomethingHappened
[2019-04-18 09:29:47][5] Processing: Illuminate\Notifications\Events\BroadcastNotificationCreated
[2019-04-18 09:29:47][5] Processed:  Illuminate\Notifications\Events\BroadcastNotificationCreated

Notice the last process. But when I set my queue connection to redis, this is what I get:

[2019-04-18 09:24:25][3] Processing: App\Notifications\SomethingHappened
[2019-04-18 09:24:25][3] Processed:  App\Notifications\SomethingHappened
[2019-04-18 09:24:25][4] Processing: App\Notifications\SomethingHappened
[2019-04-18 09:24:26][4] Processed:  App\Notifications\SomethingHappened
[2019-04-18 09:24:25][1] Processing: App\Notifications\SomethingHappened
[2019-04-18 09:24:25][2] Processing: App\Notifications\SomethingHappened
[2019-04-18 09:24:27][2] Processed:  App\Notifications\SomethingHappened
[2019-04-18 09:24:28][1] Processed:  App\Notifications\SomethingHappened

What mistake did I make?

08 Apr
3 months ago
07 Apr
3 months ago

tanmay_das started a new conversation Laravel Echo Presence Channel Not Working

I have this simple presence channel:

Broadcast::channel('test', function ($user) {
    return ['id' => $user->id, 'name' => $user->name];
});

I am trying to join the channel from the client side. In my vue component's mounted() hook, I am doing the following:

window.Echo.join('test')
      .here( users => console.log(users))

In the destroyed() hook, I am doing the following:

window.Echo.leave('test');

But nothing is logged in the console when I navigate to that component. What am I missing?

Public and Private channels are working fine though. I do not have any event associated with the presence channel. I am using laravel-websockets package. Feel free to ask me more info.

28 Nov
7 months ago

tanmay_das left a reply on SPA Redirection In Laravel + Vue

at some point the user comes back on your return_url, with some payment ID in the GET params

The return url I have set is the backend url (http://localhost:8000/api/success) because the gateway POSTs those payment ID and status etc. to my server. So, I am guessing in my controller's method of api/success route, I would have to perform a return redirect('http://localhost:8080');?

tanmay_das started a new conversation SPA Redirection In Laravel + Vue

I have the following situation:

I have an SPA, front-end is built with vue and back-end is built with laravel. Now I have a problem.

  1. I need to redirect my user to payment gateway with some post data
  2. Once the transaction is completed/canceled/failed, I will have to bring him/her back to the application with another set of post data that was sent by the gateway to my server (back-end)

My front-end is running on: http://localhost:8080

And the back-end is on: http://localhost:8000

I am using axios to perform http requests in the frontend.

My problem is in task #1. I cannot perform the redirection using a form and hidden inputs because the gateway url requires store_id and store_password params which I cannot put in a form. Also window.location is not very helpful since I cannot post data using it.

How can I handle this?

09 Oct
9 months ago

tanmay_das started a new conversation How To Get LocalStorage Working In Vue Testing

I am trying to test vue components.

I have a vue single file component which uses vuex. My states are stored in store.js which makes use of localStorage. However, when I run npm test I get error that reads:

WEBPACK Compiled successfully in 9416ms

MOCHA Testing...

RUNTIME EXCEPTION Exception occurred while loading your tests

ReferenceError: localStorage is not defined

Tools I am using for testing: @vue/test-utils, expect, jsdom, jsdom-global, mocha, mocha-webpack

How I run the tests:
"test": "mocha-webpack --webpack-config node_modules/laravel-mix/setup/webpack.config.js --require tests/JavaScript/setup.js tests/JavaScript/**/*.spec.js"

A sample test, order.spec.js:

require('../../resources/assets/js/store/store');
require('../../resources/assets/js/app');
import { mount } from '@vue/test-utils';
import Order from '../../resources/assets/js/views/order/List.vue';
import expect from 'expect';

describe('Order', ()=>{
    it('has alert hidden by default', () => {
        let wrapper = mount(Order);
        expect(wrapper.vm.alert).toBe(false);
    })
})

In setup.js file I am loading jsdom like this:

require('jsdom-global')();

How do I fix this?

13 Sep
10 months ago

tanmay_das left a reply on What To Do When Paginator Is Not Allowed On A Collection?

@Vilfago Thanks for you reply. I tried the second option, but it only returns two rows. Should I call it on Tag or PostTag? If I call it on PostTag, whereHas('posts') isn't going to work because there is no relation called posts in PostTag. I really wish I could tackle this in an Eloquent-friendly way, rather than Collection-manipulating way :(

tanmay_das started a new conversation What To Do When Paginator Is Not Allowed On A Collection?

I have two entities: Post (posts) and Tag (tags). They both are in many-to-many relationship. So I have a pivot table called PostTag (post_tag). I want to list all the tags [including a) pivot table and b) post title] which belong to those posts whose author is the logged in user. So I did something like this:

$tags = collect();
$posts = Post::where('user_id', auth()->id())->with('tags')->get();
$posts->each(function($post, $key) use ($tags){
    $post->tags->each(function($tag, $key) use ($tags, $post) {
        $tag->post_title = $post->title;
        $tags->push($tag);
    });
});
return $tags;

However, I also need to paginate the result. So I attempted to return this instead:

return $tags->paginate(10);

But paginate is not a method of Collection (Maybe of Builder)

The relationship methods are:

// Post.php
public function tags() {
    return $this->belongsToMany(Tag::class)->withPivot('updated_at');
}
// Tag.php
public function posts(){
    return $this->belongsToMany(Post::class);
}

I have a feeling that there must be some easier way of doing it which I may not know:

PostTag::someQueryThatFetchesThoseTagsWithPostTitle();
// If I could do something like this, paginate() would have been available
26 Jul
11 months ago

tanmay_das left a reply on Accessing User Roles From Vue In An SPA

Consider this scenario:

<p v-if="Auth.is('admin')">This is a very sensitive info and only the admin is meant to see it </p>
<p v-else> You are not an admin </p>

What if a user opens up the console and runs Laravel.user.roles.push('admin')?

How did/would you tackle that?

24 Jun
1 year ago
06 Jun
1 year ago

tanmay_das left a reply on Laravel Global Query Scope's WithoutGlobalScope() Not Returning Desired Records

Turns out when I use the full class path, then it works:

App\MyModel::withoutGlobalScope('App\Scopes\ArchiveScope')->get();

Previously I have been using this:

App\MyModel::withoutGlobalScope(ArchiveScope::class)->get();

...as the documentation suggested.

I am using PHP 7.2.5.

tanmay_das left a reply on Laravel Global Query Scope's WithoutGlobalScope() Not Returning Desired Records

Hi @bobbybouwmann Thanks for your reply.

I followed the documentation step by step. Here is my scope that resides in app/Scopes directory:

<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class ArchiveScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('archived_at', '=', NULL);
    }
}

And this is how I am using it inside my model:

/**
     * The "booting" method of the model.
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope(new ArchiveScope);
    }

Also, I am using soft deletion for that model. Is there a possibility of conflict with laravels scope for soft deletion?

tanmay_das started a new conversation Laravel Global Query Scope's WithoutGlobalScope() Not Returning Desired Records

I have a global query scope called ArchiveScope that mimics the similar functionality of Soft Deletion. The apply method of that scope looks like this:

    public function apply(Builder $builder, Model $model)
    {
        $builder->where('archived_at', '=', NULL);
    }

So when I use MyModel::all(), it returns all the rows that do not have a timestamp (i.e. NULL). But when I want to fetch all the records (including archived), I still get the same result. I am running this statement in the tinker:

App\MyModel::withoutGlobalScope(ArchiveScope::class)->get();

Strangely, when I use withoutGlobalScopes() instead of withoutGlobalScope(ArchiveScope::class) then I get all the records.

App\MyModel::withoutGlobalScopes()->get();

28 Apr
1 year ago

tanmay_das left a reply on DOMException: Invalid Header Name.

Having the same issue here. Let me know if you've solved it.

16 Feb
1 year ago

tanmay_das left a reply on Confusions About Laravel Storage Directory And Its Symlink

Anything that's visible in the browser, shouldn't it be considered public? And if that's the case, shouldn't logo, banner etc. be considered public too?

tanmay_das left a reply on Confusions About Laravel Storage Directory And Its Symlink

@mhankins It's not working. Maybe because it's pointing to /media/tanmay/3806FF1D11D87FF6/code/myapp/storage/app/private/logo.png, which translates into this:

http://localhost:3000/media/tanmay/3806FF1D11D87FF6/code/myapp/storage/app/private/logo.png

instead of being translated into this:

http://localhost:3000/storage/app/private/logo.png

...relative to my application, not my entire disk (media/tanmay/blah/....).

And I just realized it will never get past the storage/app directory, since the symlink in the public (http://localhost:3000/) directory is always pointing to storage/app/public/

The only solution I can see is to put my private assets in public directory :(

tanmay_das started a new conversation Confusions About Laravel Storage Directory And Its Symlink

Okay, this is what I understand about the laravel storage so far:

All my public assets, things like profile pictures or any user-generated files should reside in myapp/storage/app/public and things that are not user-generated, but application-specific, such as: logo, banner etc., should reside outside the public directory. For instance, myapp/storage/app/private.

We create a symlink within the myapp/public/ directory that points to myapp/storage/app/public/ and we access our public assets by asset('storage/avatar.png'). It loads the avatar from storage/app/public/avatar.png

But how do I access my private assets? Say I want to load my logo.png file which is in storage/app/private/logo.png this path?

20 Jan
1 year ago

tanmay_das left a reply on Image Validation Rules Example

Are you sure you didn't add it to a different form? Because 3 days ago, I had exactly the same issue and it was caused by the misplacement of the enctype attribute: https://laracasts.com/discuss/channels/laravel/laravel-multi-file-validation-fails

tanmay_das left a reply on Image Validation Rules Example

In your opening <form> tag, add enctype="multipart/form-data" attribute.

19 Jan
1 year ago

tanmay_das left a reply on Route Exists But Page Not Found

Is it because ->firstOrFail()?

tanmay_das started a new conversation Route Exists But Page Not Found

I have a route:

Route::get('generateresult', '[email protected]n');

[email protected]:

public function gen(){
        $examinees = \App\Examinee::all();
        foreach ($examinees as $examinee) {
            $result = new Result();
            $result->name = $examinee->user->name;
            $result->email = $examinee->user->email;
            $result->institution = $examinee->institution;
            $result->answered = count($examinee->user->submittedAnswers()->get());
            $result->correct = $examinee->user->get_correct_answers($examinee->user->id);
            $result->submitted_at = $examinee->user->submittedAnswers()->firstOrFail()->created_at;
            $result->save();
        }
    }

When i hit generateresult route, I get a page not found error. But if I return a string from gen() method, the string is displayed properly. What went wrong?

tanmay_das started a new conversation How To Add UTC +6:30 To A Carbon Instance

I have a couple of row in a table with created_at timestamp. I want to show the value of created_at field in my view:

{{ $model->created_at }}

But this displays the default timezone it used during save(). How can I now adjust that timezone just to 'display' as if it was recorded with utc +6:30?

17 Jan
1 year ago

tanmay_das left a reply on How To Determine From And To In A Messaging Application

@mstnorris Thanks for the tip, but setting or retrieving is not what I needed. I am looking for a way to "distinguish" sender from recipient and vice versa. What would be a common approach to determine to whom I am sending the message?

Currently this is what I am doing:

1. I set up a `Route::post` like this `/message/{to}` 2. A user opens a message thread (within which, he can also reply). I set the `from` to whoever the currently logged in user is, by calling `auth()->id()` 3. I fetch the row of the last message. If the id of currently logged in user is found in either of `to` or `from` field, I set the value of the opposite column as recipient (`to`).

Is this a good approach?

tanmay_das left a reply on Laravel Multi File Validation Fails

@morteza Yeah I added enctype attr to the wrong form. My mistake :)

16 Jan
1 year ago

tanmay_das started a new conversation Laravel Multi File Validation Fails

I have a multiple file input field:

<input type="file" id="documents" name="documents[]" multiple>

In ProjecRequest:

    $rules = [
      'documents.*' => 'mimes:doc,pdf,jpeg,bmp,png|max:20000',
    ];
    return $rules;

In [email protected]:

    public function store(ProjectRequest $request)
    {
       $project = Project::create([
         /*key=>value removed to keep the question clean*/
       ]);

       foreach ($request->documents as $document) {
           $filename = $document->store('documents');
           Document::create([
              'project_id' => $project->id,
              'filepath' => $filename
           ]);
       }
       return redirect()->back();
    }

But when I try to upload a png or pdf I get the following validation error:

The documents.0 must be a file of type: doc, pdf, jpeg, bmp, png.

14 Jan
1 year ago

tanmay_das started a new conversation How To Determine From And To In A Messaging Application

My message table looks like this:

message(id, from, to, body, is_seen).

Here, both from and to are the ids of the user table. I can always determine the from id by calling auth()->id() but how do I fill up the to column?

10 Jan
1 year ago

tanmay_das left a reply on Whoops! Class App\Http\Controllers\Type Does Not Exist

It looks like your editor is trying to be ultra-smart and putting the Type $var = null placeholder in each of the methods.

Change this:

class PagesController extends Controller
{
    public function getIndex(Type $var = null)
    {
        return view('pages.welcome');
    }

    public function getAbout(Type $var = null)
    {
        return view('pages.about');
    }

    public function getContact(Type $var = null)
    {
        return view('pages.contact');
    }

}

To this:

class PagesController extends Controller
{
    public function getIndex()
    {
        return view('pages.welcome');
    }

    public function getAbout()
    {
        return view('pages.about');
    }

    public function getContact()
    {
        return view('pages.contact');
    }

}
08 Jan
1 year ago

tanmay_das started a new conversation Laravel Shared Hosting Deployment

I have a copy of my project in my office pc and I pushed the project to a bitbucket git repo. I have been instructed to deploy the project as soon as I go home. I came to home and:

  1. Cloned the repo to home pc. It didn't have the vendor directory as it is ignored by the gitignore file

  2. A quick google search suggested me to run composer install, but it didn't work because of unmet requirements

  3. So I ran composer update instead and it regenerated the vendor directory. Meanwhile, I already uploaded everything else except the vendor directory

  4. gitignore also ignores the .env file, so I duplicated .env.example and renamed it to .env and generated a key using php artisan key:generate and uploaded the file to the server

  5. I am currently at this stage, about to upload the vendor directory. It contains a lot of files and will consume a huge amount of time. If anyone could confirm that all the above steps were ok and I did not ruin anything I would upload the vendor directory

06 Jan
1 year ago

tanmay_das left a reply on Blade Nested Section Produces Misformatted DOM

@calder12 Thanks but don't you think this is anti-DRY? I mean for every single page, I would have to create a different sidebar x_sidebar, y_sidebar, z_sidebar and so on...

tanmay_das left a reply on Can Anyone Please Tell Me The Font Name

In headings, they are using Roboto. In paragraphs, Open Sans Light.

tanmay_das started a new conversation Blade Nested Section Produces Misformatted DOM

Here is the content of my home.blade.php file:

@extends('layouts.master')
@section('content')
  @extends('partials.sidebar')
    @section('pagecontent')
      This is home
    @endsection
@endsection

layouts/master.blade.php contains the main layout which has the typical <html><head><body> structure. In it's <body>, I am yielding to a section called content:

<!DOCTYPE html> 
<html>
<body>
  <div id="app">
    @yield('content')
  </div>
</body>
</html>

and in my parials/sidebar.blade.php, I am yielding to a section called pagecontent:

<div id="page-content-wrapper">
        <div class="container-fluid">
            @yield('pagecontent')
        </div>
</div>

So I would naturally expect a DOM like this:

<!DOCTYPE html> 
<html>
<body>
  <div id="app"> <!-- @section('content') -->
    <div id="page-content-wrapper">
        <div class="container-fluid">
            This is home <!-- @section('pagecontent') -->
        </div>
   </div>
  </div>
</body>
</html>

Unfortunately, that's not the DOM my blade views are rendering. My sidebar partial doesn't get injected inside the master layout, instead, it is appended to the DOM as a sibling of the Entire Document:

<div id="page-content-wrapper">
   <div class="container-fluid">
       This is home <!-- @section('pagecontent') -->
   </div>
</div>

<!DOCTYPE html> 
<html>
<body>
  <div id="app"> <!-- @section('content') -->
  </div>
</body>
</html>

How can I fix this?

24 Dec
1 year ago

tanmay_das left a reply on Implementing Reset Password Feature Without Make:auth

I am not manually creating the link, the link gets generated by (ResetPassword)[https://laravel.com/api/5.4/Illuminate/Auth/Notifications/ResetPassword.html] Notification:

    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->line('You are receiving this email because we received a password reset request for your account.')
            ->action('Reset Password', url(config('app.url').route('password.reset', $this->token, false)))
            ->line('If you did not request a password reset, no further action is required.');
    }

tanmay_das left a reply on Implementing Reset Password Feature Without Make:auth

But why is laravel generating the link with a query string? It doesn't happen with the make:auth. I just tested. With make:auth, it's generated as reset/$token and not as reset?$token

tanmay_das left a reply on Implementing Reset Password Feature Without Make:auth

Interestingly, when I change my reset link from this:

http://localhost:8000/password/reset?8331031f0abcf4686ec143483fff403d5d9adbc893c6d20292ffb99c913e9e01

to this:

http://localhost:8000/password/reset/8331031f0abcf4686ec143483fff403d5d9adbc893c6d20292ffb99c913e9e01

Then the reset view loads! What should I do?

tanmay_das left a reply on Implementing Reset Password Feature Without Make:auth

I believe the source of the problem is in this route:

Route::get('/password/reset/{token}', '[email protected]')->name('password.request');

Somehow it's failing to receive the $token, hence the redirection. As mentioned in the ResetsPasswords trait:

/**
     * Display the password reset view for the given token.
     *
     * If no token is present, display the link request form.
     *

tanmay_das left a reply on Implementing Reset Password Feature Without Make:auth

Something went wrong. I can send the reset email. But for some reason when I click on the reset password link, I get redirected back to showLinkRequestForm() method. Here is what I have done so far:

My routes:

Route::get('/password/reset', '[email protected]')->name('password.email');

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

Route::get('/password/reset/{token}', '[email protected]')->name('password.request');

Route::post('/password/reset', 'ResetPasswordCon[email protected]')->name('password.reset');

ForgotPasswordController.php:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;

class ForgotPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset emails and
    | includes a trait which assists in sending these notifications from
    | your application to your users. Feel free to explore this trait.
    |
    */

    use SendsPasswordResetEmails;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    public function showLinkRequestForm()
    {
        return view('password.email');
    }
}

ResetPasswordController.php:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    public function showResetForm(Request $request, $token = null)
    {
        return view('password.reset')->with(
            ['token' => $token, 'email' => $request->email]
        );
    }
}

password.email view (this one loads perfectly):

@extends('layouts.master')
@section('content')
    <div class="col-sm-8 offset-sm-2">
        <h1>Forgot Password</h1>
        <form method="POST" action="/password/email">
            {{ csrf_field() }}
            <div class="form-group">
            <label for="email">E-mail</label>
            <input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
          </div>
          <button type="submit" class="btn btn-primary">Send Password Reset Link</button>
        </form>
    </div>
@endsection

password.reset view (this one does not):

@extends('layouts.master')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Reset Password</div>

                <div class="panel-body">
                    <form class="form-horizontal" method="POST" action="{{ route('password.request') }}">
                        {{ csrf_field() }}

                        <input type="hidden" name="token" value="{{ $token }}">

                        <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
                            <label for="email" class="col-md-4 control-label">E-Mail Address</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control" name="email" value="{{ $email or old('email') }}" required autofocus>

                                @if ($errors->has('email'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('email') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
                            <label for="password" class="col-md-4 control-label">Password</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control" name="password" required>

                                @if ($errors->has('password'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('password') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }}">
                            <label for="password-confirm" class="col-md-4 control-label">Confirm Password</label>
                            <div class="col-md-6">
                                <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>

                                @if ($errors->has('password_confirmation'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('password_confirmation') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Reset Password
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

tanmay_das left a reply on Implementing Reset Password Feature Without Make:auth

@Snapey There are two controllers for password reset: 1. ForgotPasswordController 2. ResetPasswordController.

If I copy these two controllers in my current project and add necessary routes like below, is it going to take care of the entire resetting process:

‍‍‍‍‍``` Route::get('password/reset', '[email protected]'); Route::post('password/email', '[email protected]'); Route::get('password/reset/{token}', '[email protected]'); Route::post('password/reset', '[email protected]');


The `ForgotPasswordController` uses the `SendPasswordResetEmails` trait, in which, the `showLinkRequestForm()` method returns a view that Laravel auto-generates during make:auth process. Can I override that method to return my own view?

And the `ResetPasswordController` uses the `ResetPasswords` trait where the `showResetForm()` also returns laravel generated view. I will have to override it too.

Am I on the right track?

tanmay_das left a reply on Implementing Reset Password Feature Without Make:auth

@Snapey Thanks, I guess I am beginning to understand the logic behind it.

I have a question though. How do I access the password_reset table that comes with laravel? I mean there is no model associated with it...

tanmay_das left a reply on Implementing Reset Password Feature Without Make:auth

@rumm.an Okay, let's say I've sent the mail with the url: mycoolsite.com/passwordreset/token/.$token

Then what? How can I track which user clicked the reset link, otherwise how would I know who is trying to reset the password?

tanmay_das left a reply on Problem With Find Out Category Name | Laravel 55

Yes, you can. But let me explain a few things first: When you execute

$categories = Category::where('id', $post->category_id)->orderBy('category_name')->get();

you always get a collection of one result, because your where clause will never return more than one row, since there is one row associated with one unique id. You can think of what you are doing now as using a bucket for only one fish.

If you expect only one fish (row) using a bucket (collection) is overkill. Instead what you could do is use your hand (methods like: first() and find()):

You can achieve this in one of the two ways:

$category = Category::where('id', $post->category_id)->get()->first();

Or:

$category = Category::find($post->category_id);

Then you can throw your fish in blade like this: {{ $category->category_name }}

tanmay_das left a reply on Problem With Find Out Category Name | Laravel 55

@NoneNameDeveloper Take a look at your variable name. It's in plural: $categories. So you are fetching a 'collection' of categories, not 'objects'.

You will have to iterate over the $categories collection like this:

@foreach($categories as $category)
    {{ $category->category_name }}
@endforeach

tanmay_das left a reply on Implementing Reset Password Feature Without Make:auth

@N3xus But how can I generate the unique reset password link?

tanmay_das left a reply on Problem With Find Out Category Name | Laravel 55

It's either categories_name or category_name. Assuming your column name is category_name and not categories_name, you should change this:

{{$categories ->categories _name}}

to this:

{{ $categories ->category _name }}