tanmay_das

Experience

9,100

0 Best Reply Awards

  • Member Since 5 Months Ago
  • 77 Lessons Completed
  • 0 Favorites

22nd August, 2017

tanmay_das started a new conversation Is It Possible To Create A FormRequest Along With The Model Using Php Artisan Make:model? • 16 hours ago

Usually, for a resource, I create the model, migration and resourceful controller all at once using php artisan make:model MyModel -mcr

Now I realized for a large application, rather than applying rules directly in the controllers method, I should separate them from the controller and keep a dedicated FormRequest class for each of the resources. But php arisan help make:model doesn't show any option for doing such a thing at the same time. So I have to run php artisan make:request MyRequest separately every time. Could you share some tips so that I could save some time and extra keystrokes?

7th August, 2017

tanmay_das left a reply on Laravel-mix - BrowserSync Throwing An Error At Event.js:160 • 2 weeks ago

Strange but if I prefix the commands with sudo, then it works

tanmay_das left a reply on Laravel-mix - BrowserSync Throwing An Error At Event.js:160 • 2 weeks ago

Here is a screenshot of my /tmp directory: http://imgur.com/a/jqFjP

I can see a lot of npm-* folders in there... most of them are empty...

tanmay_das left a reply on Laravel-mix - BrowserSync Throwing An Error At Event.js:160 • 2 weeks ago

@36864 Thanks for your reply. But how can my /tmp directory be full? I installed the OS last night. If the directory is full, how is it that when I create a new laravel project and run the same mix.js file (I mean with browserSync() call), the npm commands run flawlessly? If a new project can pull in the browserSync() dependencies, why should an old project fail?

tanmay_das left a reply on Laravel-mix - BrowserSync Throwing An Error At Event.js:160 • 2 weeks ago

Question updated...

tanmay_das started a new conversation Laravel-mix - BrowserSync Throwing An Error At Event.js:160 • 2 weeks ago

Not sure if the problem is related to laravel-mix, but I am having problem with Browsersync package. Here is my mix.js:


mix.js('resources/assets/js/app.js', 'public/js')
   .browserSync({proxy: 'localhost:8000'})
   .sass('resources/assets/sass/app.scss', 'public/css');

When I run npm run watch-poll ( watch doesn't pick up the changes, hence the watch-poll) I get the following error on the console:


[Browsersync] Watching files...
events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: watch resources/views/auth/passwords ENOSPC
    at exports._errnoException (util.js:1020:11)
    at FSWatcher.start (fs.js:1443:19)
    at Object.fs.watch (fs.js:1470:11)
    at createFsWatchInstance (/home/tanmay/LVProjects/learningdemo/node_modules/chokidar/lib/nodefs-handler.js:37:15)
    at setFsWatchListener (/home/tanmay/LVProjects/learningdemo/node_modules/chokidar/lib/nodefs-handler.js:80:15)
    at FSWatcher.NodeFsHandler._watchWithNodeFs (/home/tanmay/LVProjects/learningdemo/node_modules/chokidar/lib/nodefs-handler.js:228:14)
    at FSWatcher.NodeFsHandler._handleDir (/home/tanmay/LVProjects/learningdemo/node_modules/chokidar/lib/nodefs-handler.js:407:19)
    at FSWatcher.<anonymous> (/home/tanmay/LVProjects/learningdemo/node_modules/chokidar/lib/nodefs-handler.js:455:19)
    at FSWatcher.<anonymous> (/home/tanmay/LVProjects/learningdemo/node_modules/chokidar/lib/nodefs-handler.js:460:16)
    at FSReqWrap.oncomplete (fs.js:123:15)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ watch: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js "--watch-poll"`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the @ watch script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/tanmay/.npm/_logs/2017-08-07T07_02_31_677Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ watch-poll: `npm run watch -- --watch-poll`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the @ watch-poll script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/tanmay/.npm/_logs/2017-08-07T07_02_31_725Z-debug.log

I am on: Ubuntu 16.04.3 (Not a VM) Using: Nodejs v6.11.2, NPM v5.3.0

13th June, 2017

tanmay_das started a new conversation Changing The Value Of 'this' Withing A Vue Method • 2 months ago

I want to simulate a notification that would disappear after 3 seconds. But within the setTimout() method, this is referring to the window object. How do I explicitly tell vue that this should refer to app, not window?

HTML:

<div id="root">
    <h1 v-show="isVisible">A new notification</h1>
</div>

VUE:

var app = new Vue({
        el: '#root',
        data: {
            isVisible: true
        },
        mounted: function(){
            setTimeout(function(){
                app.isVisible = false;
            }, 3000);
            // console.log(this.isVisible);
        }
});

This Works. But this does not:

var app = new Vue({
        el: '#root',
        data: {
            isVisible: true
        },
        mounted: function(){
            setTimeout().call(app, function(){
                this.isVisible = false;
            }, 3000); // Am I calling it the right way?!?
        }
});

27th May, 2017

tanmay_das left a reply on Computed Property Within A Vue.component() • 2 months ago

This fixes the problem: template: '<div v-bind:class="setClass"><slot></slot></div>'

tanmay_das left a reply on Computed Property Within A Vue.component() • 2 months ago

@jimmck The classes aren't being applied. In fact, I don't think the function setClass() is being invoked at all! I tried to execute console.log('If you can see me, setClass func is being called'); inside the setClass() method. Nothing showed up in the console :(

tanmay_das started a new conversation Computed Property Within A Vue.component() • 2 months ago

Hi, I am learning Vue.js 2.0. I want to create a custom component like this: <bs-container fluid="true"></bs-container> and I would like Vue.component() to take care of the bootstrap 3 container classes behind the scenes based on the boolean value passed in the fluid props, because <bs-container fluid="true"></bs-container> looks much cleaner than div class="container-fluid></div>. This is my attempt so far, but it's not working:

HTML:

<div id="app" >
    <bs-container fluid="false">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</bs-container>
</div>

VueJS:

Vue.component('bs-container',{
    props: ['fluid'],
    template: '<div class="setClass"><slot></slot></div>',
    computed: {
        setClass: function() {
            if (this.fluid == true) { //Am I accessing fluid properly!?!
                return 'container-fluid';
            } else{
                return 'container';
            }
        }
    }
});

new Vue({
    el: '#app'
})

How can I achieve this?

27th April, 2017

tanmay_das left a reply on Checking Password Hash To Update Password • 3 months ago

@Screenbeetle Thanks, it works: password_verify($request->oldpassword, $seller->password)

tanmay_das left a reply on Checking Password Hash To Update Password • 3 months ago

@Screenbeetle Thanks for letting me know. How should I do it then? :)

tanmay_das started a new conversation Checking Password Hash To Update Password • 3 months ago

I have a controller action like this:

public function passwordUpdate(\App\Seller $seller, Request $request){
            dd($request->oldpassword);
        if(bcrypt($request->oldpassword) == $seller->password){
            $seller->password = bcrypt($request->newpassword);
            $seller->save();
        }
        return redirect()->back();
}

The if condition here never gets executed, because the hashes for $seller-password and bcrypt($request->oldpassword) are never the same. How do I check if the $request->oldpassword really is the currently set password?

tanmay_das left a reply on Accessing Property From An Array Of Records • 3 months ago

@fahad Thanks a lot, that nested foreach loop crossed my mind but I was so depressed that I ignored it earlier. On an unrelated note, it's really good to see an user from my country here in Laravel :) :)

tanmay_das left a reply on Accessing Property From An Array Of Records • 3 months ago

@YewNork Here is the dd() output:

array:1 [▼
  0 => Collection {#255 ▼
    #items: array:1 [▼
      0 => Seller {#262 ▼
        #fillable: array:6 [▶]
        #hidden: array:2 [▶]
        #connection: null
        #table: null
        #primaryKey: "id"
        #keyType: "int"
        +incrementing: true
        #with: []
        #perPage: 15
        +exists: true
        +wasRecentlyCreated: false
        #attributes: array:12 [▼
          "id" => 1
          "name" => "Tanmay Das"
          "email" => "[email protected]"
          "password" => "$2y$10$3nFssVs5N3L5JD0kk2wLU.mYmLQlja6DdztHcPcyhcCqRMouiL7zu"
          "address" => "North Kattali, Chittagong"
          "phone_no" => "01759759461"
          "isbanned" => "0"
          "propic" => "public/sellerpropic/aUTiUQodEmpBqGs6DaidAG0TAidzEgilKORQ4kDo.jpeg"
          "remember_token" => null
          "created_at" => "2017-04-27 14:43:31"
          "updated_at" => "2017-04-27 14:43:31"
          "deleted_at" => null
        ]
        #original: array:12 [▼
          "id" => 1
          "name" => "Tanmay Das"
          "email" => "[email protected]"
          "password" => "$2y$10$3nFssVs5N3L5JD0kk2wLU.mYmLQlja6DdztHcPcyhcCqRMouiL7zu"
          "address" => "North Kattali, Chittagong"
          "phone_no" => "01759759461"
          "isbanned" => "0"
          "propic" => "public/sellerpropic/aUTiUQodEmpBqGs6DaidAG0TAidzEgilKORQ4kDo.jpeg"
          "remember_token" => null
          "created_at" => "2017-04-27 14:43:31"
          "updated_at" => "2017-04-27 14:43:31"
          "deleted_at" => null
        ]
        #casts: []
        #dates: []
        #dateFormat: null
        #appends: []
        #events: []
        #observables: []
        #relations: []
        #touches: []
        +timestamps: true
        #visible: []
        #guarded: array:1 [▶]
        #rememberTokenName: "remember_token"
      }
    ]
  }
]

tanmay_das left a reply on Accessing Property From An Array Of Records • 3 months ago

Here it is @fahad :

<div class="list-group">
                        @foreach($sellers as $seller)
                            
                                    <a href="#" class="list-group-item">From: {{ $seller->email }}</a>
                  
                        @endforeach
</div>

tanmay_das started a new conversation Accessing Property From An Array Of Records • 3 months ago

I have a route defined like this:

Route::get('/buyer_home', function(){
    $senders = \App\Message::where(['to' => \Auth::guard('web_buyer')->user()->username])->distinct()->get(['from']);
    $sellers = array();
    foreach ($senders as $sender) {
        $sellers[] = \App\Seller::where('email', $sender->from)->get();
    }
      return view('buyer.home', compact('sellers', 'senders'));
});

I am in a situation where I need to access the columns/properties of the sellers table/model in my view to establish a condition like this: @if(sender->from == seller->email). But I am getting Property [email] does not exist on this collection instance. error message when I try to access the email property of each of the sellers result within a @foreach loop. All I am intending to do is pass the list of the sellers to the view, and only those sellers who have the email that matches email returned from $sender->from. How do I tackle this?

23rd April, 2017

tanmay_das left a reply on Displaying Stored Images On Shared Hosting • 3 months ago

@Snapey How do I upload them in the public directory? Currently when I call the store method, I call it this way: ->store('public/myfolder1'); and that uploads the file to storage/app/public/myfolder1 in this folder.

My document root is: /public_html/mydomain.com/ what would be the passed argument for the store() method, if I wanted to store an image, say on /public_html/mydomain.com/imgs/myfolder1 ?

tanmay_das left a reply on Displaying Stored Images On Shared Hosting • 3 months ago

But people keep telling about all this 'Conventions' and 'Best Practices' where they suggest not to put them in public folder?

tanmay_das left a reply on Displaying Stored Images On Shared Hosting • 3 months ago

On local environment I would run php artisan storage:link to create a symlink, but I cannot run it on server due to the hosting plan limitation. Any other way to create the symlink? I have the SSH access though.

tanmay_das started a new conversation Displaying Stored Images On Shared Hosting • 3 months ago

I have successfully deployed my first laravel application on a live server. Everything looks great except the fact that I am unable to display the images that are being uploaded to the storage/app/public/myfolder1 folder.

Here is my folder hierarchy on HostGator:

/myproject_src/ : Here are all the laravel source files (except the public folder) /public_html/mydomain.com/ : Here goes all my contents of the public directory

I am storing the file path into the database in the following manner:

public/myfolder1/FxEj1V1neYrc7CVUYjlcYZCUf4YnC84Z3cwaMjVX.png

What should I do in order to display the images properly in a img tag:

<img src="{{ how to point to the uploaded image here }}">

21st April, 2017

tanmay_das left a reply on Inserting Checkbox Value Into Database • 4 months ago

->create(['isnegotiable' => request()->has('isnegotiable')])

it doesn't work because laravel treats the given value as a column, not the `isnegotiable' that we are trying to pass.

Throws this error: Column not found: 1054 Unknown column '1' in 'field list'

tanmay_das left a reply on Inserting Checkbox Value Into Database • 4 months ago

@EventFellows The problem is I am allowing user to leave the checkbox unselected which means when the form is submitted, $request object will not create any isnegotiable property, so dd($request->all()) probably will not output the isnegotiable variable. Hence, I am compelled to add it manually to the $request object.

Another solution could be using javascript to check if the checkbox is 'unselected' and if so, maybe I could append a value to the $request object through a hidden input. But that's just too much work I guess...

tanmay_das left a reply on Inserting Checkbox Value Into Database • 4 months ago

Doing it this way right now:

if(request()->has('isnegotiable') === false){
        $request->request->add(['isnegotiable' => false]);
}

//and create() method goes like this:

Item::create(['value1', 'value2', 'isnegotiable', 'anothervalue']);

but I am looking forward to a nicer solution:

tanmay_das left a reply on Inserting Checkbox Value Into Database • 4 months ago

Nope, that generated yet another error because laravel now treats the value, which is '1' as an entire column: Column not found: 1054 Unknown column '1' in 'field list'

tanmay_das left a reply on Inserting Checkbox Value Into Database • 4 months ago

@edoc Looks like I have to wrap it with quotes like this: create(['isnegotiable' => request()->has('isnegotiable')])? because I am getting this error: Use of undefined constant isnegotiable - assumed 'isnegotiable'

tanmay_das left a reply on Inserting Checkbox Value Into Database • 4 months ago

How can I solve the issue other than programmatically checking if $request->isnegotiable == null (in case the user did not select the checkbox) and then manually setting $request->isnegotiable = true in my controller?

tanmay_das started a new conversation Inserting Checkbox Value Into Database • 4 months ago

In my view I have a checkbox like this:

<input type="checkbox" name="isnegotiable" value="1"> Negotiable

And in my migration file I am setting the default value of this field to 0:

$table->boolean('isnegotiable')->default(false);

My intention is to set this value to 1 only when the user selects the checkbox. But it turns out, even if the user selects the checkbox, isnegotiable column gets filled with 0, not 1.

Because I cannot pass the isnegotiable as the argument of create(request()) method as it throws isnegotiable column cannot be null error. What should I do?

19th April, 2017

tanmay_das started a new conversation Understanding The 'this' Keyword Inside Vue Instance • 4 months ago

I have started to learn VueJS from scratch. I am following their official Guide. But I am stuck here: https://vuejs.org/v2/guide/#Handling-User-Input

In this example...

var app5 = new Vue({
  el: '#app-5',
  data: {
    message: 'Hello Vue.js!'
  },
  methods: {
    reverseMessage: function () {
      this.message = this.message.split('').reverse().join('')
    }
  }
})

...how is it that the message property is directly being accessed without any reference to the data object? If this keyword refers to the current Vue instance, shouldn't the message property be accessed like this: this.data.message ?

({
  name: "John Doe",
  data: {
    message: "Hello World"
  },
  greet: function(){
    console.log("I am " + this.name);
    console.log("I have a message for you: " + this.data.message); //see here
  }
}).greet();

This is how I would have accessed a property in vanilla javascript

17th April, 2017

tanmay_das left a reply on Overriding Logout() Method • 4 months ago

I am overriding like this:

public function logout(Request $request)
    {
        $this->guard('web_buyer')->logout();

        return redirect('/');
    }

And that logs out buyers only. Is this approach correct?

tanmay_das started a new conversation Overriding Logout() Method • 4 months ago

I have implemented custom Buyer model for the authentication. My logincontroller class looks like this:

class LoginController extends Controller
{
    //Where to redirect buyer after login.
    protected $redirectTo = '/buyer_home';

    //Trait
    use AuthenticatesUsers;

    //Custom guard for buyer
    protected function guard()
    {
      return Auth::guard('web_buyer');
    }

    //Shows buyer login form
   public function showLoginForm()
   {
       return view('buyer.auth.login');
   }
}

Where I haven't overridden login() or logout() method of AuthenticatesUsers trait. But I think I need to override the logout() method because when the buyer logs out, the default logout() method logs out any kind of users (e.g, admin, moderator etc) who are logged in.

Now my question is how do I tell Laravel that only logout the Buyer, not any other user. The logout() method in AuthenticatesUsers trait is like this:

   public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->flush();

        $request->session()->regenerate();

        return redirect('/');
    }

16th April, 2017

tanmay_das left a reply on Dynamic Route Path In Form Action Based On The Selected Option • 4 months ago

Waiting for someone to rescue me :(

tanmay_das started a new conversation Dynamic Route Path In Form Action Based On The Selected Option • 4 months ago

I have a form like this in laravel 5.4 view:

<form action="#" method="POST" class="form-inline" role="form">
        {{ csrf_field() }}
            <div class="form-group">
                <select id="tdcategory" class="selectpicker show-tick show-menu-arrow" onchange="this.form.submit()">
                  @foreach($categories as $category)
                        <option value="{{ $category->id }}">{{ $category->name }}</option>
                  @endforeach
                </select>
            </div>
            <div class="form-group">
            <select id="tdlocation" class="selectpicker show-tick show-menu-arrow" onchange="this.form.submit()">
                @foreach($locations as $location)
                    <option value="{{ $location->id }}">{{ $location->name }}</option>
                @endforeach
            </select>
            </div>
</form>

I have two questions:

  1. How can I dynamically set the form action to something like

    categories/{category->id}/locations/{location->id}

Where, both category id and location id will be based on the value of the option the user has currently selected

  1. Since the form gets submitted as the user changes the option, the page is then reloaded and resets both of the <select> tag. How do I keep track of previously selected option and as the page loads, I can show the user which one did he/she select before the form was submitted?

15th April, 2017

tanmay_das started a new conversation How Does Knowing VueJS Make Front-end Life Easier • 4 months ago

I am trying to learn VueJS. But why should one learn VueJS? What are some circumstances where you thought you really needed something like VueJS?

tanmay_das left a reply on How To Properly Display Json Response In View • 4 months ago

I closely looked one last time at the returned JSON data and realized that I have to call the $.each() method on data['data'] and not on the entire data object that solved my problem

$('#tdcategory').on('change',function(e){
        //console.log(e);
        var cat_id = e.target.value;
        $.get('/fetchads?cat_id=' + cat_id, function(data) {
            $.each(data['data'], function(index, ads){
                    console.log(ads.name);
            });
        });
    });

Yields: Antoher worthless ad :)

tanmay_das started a new conversation How To Properly Display Json Response In View • 4 months ago

I am trying to display the content that came from a ajax request in laravel. Here is my action in controller:

public function fetch(){
        $cat_id = request('cat_id');
        $ads = Item::whereCategory($cat_id)->orderBy('price', 'asc')->paginate(3);

        // return view('ads')->with('ads', json_decode($ads, true));
        return response()->json($ads);
    }

Here is the Route::get method in web.php file:

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

This is my ajax call:

$('#tdcategory').on('change',function(e){
        var cat_id = e.target.value;
        $.get('/fetchads?cat_id=' + cat_id, function(data) {
            console.log(data.name);
        });
});

And here is my JSON response:

{
    "total": 1,
    "per_page": 3,
    "current_page": 1,
    "last_page": 1,
    "next_page_url": null,
    "prev_page_url": null,
    "from": 1,
    "to": 1,
    "data": [
        {
            "id": 3,
            "name": "Antoher worthless ad",
            "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec at libero tortor. Fusce posuere ac neque sed placerat. Donec lectus magna, consequat et eros vel, luctus placerat magna.",
            "seller_id": "1",
            "used_for": "1 month",
            "price": 60000,
            "isnegotiable": 1,
            "subcategory_id": 3,
            "sublocation_id": 2,
            "created_at": "2017-04-11 10:48:09",
            "updated_at": "2017-04-11 10:48:09"
        }
    ]
}

console.log prints out undefined

14th April, 2017

tanmay_das started a new conversation Determining Recursive Url In Blade • 4 months ago

I am not at all ashamed of admitting that I am new to Laravel and my method of determining dynamic URL in Blade might look somewhat silly or maybe I am doing it the wrong way. Please correct me if I am and guide me if possible.

Here is what I am trying to achieve: I have two menus in my view for the end-users: 1) Categories 2) Locations. When the user clicks on any of the categories or locations, the URL changes from this http://localhost:8000 to this (say he/she clicked on a category):

http://localhost:8000/categories/1

And while the user is viewing the contents of http://localhost:8000/categories/1 this URL, he now wishes to click on a location, and this time the URL looks like this:

http://localhost:8000/categories/1/locations/1

Now he wants to change the location. His expected URL:

http://localhost:8000/locations/2

But instead it becomes:

http://localhost:8000/categories/1/locations/1/locations/2

That's my problem. How can I reset the URL back to / so that the user can visit his desired URL: http://localhost:8000/locations/2, when he has already reached http://localhost:8000/categories/{id}/locations/{id} or http://localhost:8000/locations/{id}/categories/{id}

Here is what I am doing in my view:

The category loop:

@foreach($categories as $category)

    @if((Request::path() == '/') or (starts_with(Request::path(),'categories/')))
        <a href="/categories/{{ $category->id }}" class="list-group-item">{{ $category->name }}</a>
    @elseif(starts_with(Request::path(),'locations/'))
        <a href="/{{ Request::path() }}/categories/{{ $category->id }}" class="list-group-item">{{ $category->name }}</a>
    @endif
@endforeach

The location loop:

@foreach($locations as $location)
    @if((Request::path() == '/') or (starts_with(Request::path(),'locations/')))
        <a href="/locations/{{ $location->id }}" class="list-group-item">{{ $location->name }}</a>
    @elseif(starts_with(Request::path(),'categories/'))
        <a href="/{{ Request::path() }}/locations/{{ $location->id }}" class="list-group-item">{{ $location->name }}</a>
    @endif
@endforeach

tanmay_das started a new conversation How To Chain Paginate() Method With Where() Methods • 4 months ago

Normally to get all the $items I am calling the paginate method like this:

$items = Item::orderBy('price', 'asc')->paginate(3);

But how can I call paginate orderBy('price', 'asc')->paginate(3) when I have something like this:

$ads = Item::where('name', 'LIKE', "%{$q}%")
    ->whereCategory($request->category)
    ->whereSublocation($request->location)
    ->get();

13th April, 2017

tanmay_das left a reply on Equivalent Eloquent Query • 4 months ago

Thanks guys, but you know what... now I have added two more tables: location and sublocation.

@bwrice If I follow your suggestion and add a hasManyThrough() relation also in the Location model, how would I then call the Category::find() and Location::find methods at a time to get all the $items?

tanmay_das started a new conversation Equivalent Eloquent Query • 4 months ago

Consider the following three tables:

  1. items (id, name, description, subcategory_id)
  2. categories (id, name)
  3. subcategories (id, name, category_id)

I am trying to implement a search functionality for my first Laravel e-commerce project. I am asking the user to provide two things to run a search: a) The query string b) The category (not subcategory)

If I had the category_id in my items table, I could have gotten away with a simple query like this:

SELECT * FROM `items` WHERE name LIKE 'A%' AND category_id = '1';

But, since the category_id is in the subcategories table I have to run a nested statement like this:

SELECT * FROM `items` WHERE name LIKE 'A%' AND subcategory_id IN (SELECT id FROM sub_categories WHERE category_id = '1')

I have the dedicated Models for each of the tables (i.e. Item, Category, Subcategory) and the relationship between the Category and Subcategory is established via the hasMany() and belongsTo() methods. How do I transform the above traditional SQL query into the equivalent Eloquent query?

7th April, 2017

tanmay_das started a new conversation Relationship Works With HasMany() But Fails With BelongsTo • 4 months ago

I have two Models.

  1. Category: `<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model { protected $fillable = [ 'name', ];

public function subcategories(){
    return $this->hasMany(SubCategory::class);
}

} `

  1. SubCateogry: `<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class SubCategory extends Model { protected $fillable = [ 'name', 'category_id', ];

public function categories(){
    return $this->belongsTo(Category::class);
}

} As the Model names suggest, one category may have multiple subcategories. My problem is when I run$c = App\Category::first(); $c->subcategories;in tinker, I get the list of sub categories that belongs to a particular category (in this case, the first() one) but when I try the inverse, which is:$s = App\SubCategory::first(); $s->category;` I get null!! But I am supposed to get the row of the category where the subcategory belongs. What am I doing wrong?

tanmay_das left a reply on How Can I Properly Display Image That Is Stored In My Storage Folder • 4 months ago

Fixed it finally, thanks :)

tanmay_das left a reply on How Can I Properly Display Image That Is Stored In My Storage Folder • 4 months ago

Yest that command created the symlink which points to this location: storage/app/public. But my asset is in this location: storage/app/sellerpropic. Which means sellerpropic directory is not a 'children' of public directory but a 'sibling' of it. What do I do?

tanmay_das started a new conversation How Can I Properly Display Image That Is Stored In My Storage Folder • 4 months ago

Hi, I stored the image inside the 'storage/app/sellerpropic' folder using store() method and saved the path in my database like: 'sellerpropic/laravel-generated-image-name.jpg'. However I am unable to use the path as my img src in the view. I have tried the following methods:

  1. Propic of {{ $seller-name }}

Result: Didn't work. N.B.: Here 'propic' property contains the value: sellerpropic/laravel-generated-image-name.jpg

  1. Propic of {{ $seller-name }}

Result: Didn't work.

  1. Propic of {{ $seller-name }}

Result: Didn't work.

Additional info: I am working in local environment. I also have created a symbolic link using the 'php artisan storage:link' command.

2nd April, 2017

tanmay_das left a reply on How To Delete Session Data? • 4 months ago

Well, then I think calling $request->session()->forget('key'); and session()->forget('key'); has the same effect in this case

tanmay_das left a reply on How To Delete Session Data? • 4 months ago

Does that mean there isn't any other way than using a $request instance? If one can store data without $request instance, he should also be able to delete the data without $request object.

tanmay_das started a new conversation How To Delete Session Data? • 4 months ago

The official documentation suggests that there are two ways to handle session in laravel. I am trying the global-session-helper way. But in the delete data section (https://laravel.com/docs/5.4/session#deleting-data) it only shows how to delete via the $request instance.

How can I delete a session data that I stored using session(['key' => 'value']);?

18th March, 2017

tanmay_das left a reply on QueryException In Connection.php Line 647: Database (database/database.sqlite) Does Not Exist. • 5 months ago

Solved the issue by replacing this line 'database' => env('DB_DATABASE', database_path('database.sqlite')), with this: 'database' => database_path('database.sqlite'),

From a beginners point of view, I find this db configuration of laravel way too complicated. There should be an out-of-the-box way to handle this :(

tanmay_das started a new conversation QueryException In Connection.php Line 647: Database (database/database.sqlite) Does Not Exist. • 5 months ago

I have been following along the Laravel 5 from scratch tutorial series and I am now stuck at lecture 7 which is about the DB migration. I was able to create table and insert rows into it from the tinker but when I try to query the db from controller I get the above-mentioned error. Here is my .env file:

APP_ENV=local APP_KEY=base64:nvSV7OF0nXn+KTsVRypOReXNSruqXb0pzBEFB/6vENw= APP_DEBUG=true APP_LOG_LEVEL=debug APP_URL=http://localhost

DB_CONNECTION=sqlite DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=database/database.sqlite DB_USERNAME=homestead DB_PASSWORD=secret

BROADCAST_DRIVER=log CACHE_DRIVER=file SESSION_DRIVER=file QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1 REDIS_PASSWORD=null REDIS_PORT=6379

MAIL_DRIVER=smtp MAIL_HOST=mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=null MAIL_PASSWORD=null MAIL_ENCRYPTION=null

PUSHER_APP_ID= PUSHER_APP_KEY= PUSHER_APP_SECRET=

And here is my sqlite config in database.php file:

'default' => env('DB_CONNECTION', 'sqlite'), ... 'sqlite' => [ 'driver' => 'sqlite', 'database' => env('DB_DATABASE', database_path('database.sqlite')), 'prefix' => '', ],

One thing that I have noticed is whatever value I assign to DB_DATABASE, the error is always pointing to database/database.sqlite. For instance even if I change the DB_DATABASE value to abc.sqlite, I will still get an InvalidArgumentException in SQLiteConnector.php line 34: Database (database/database.sqlite) does not exist. [at SQLiteConnector->connect(array('driver' => 'sqlite', 'database' => 'database/database.sqlite', 'prefix' => '', 'name' => 'sqlite')) in ConnectionFactory.php line 221]

Edit Your Profile
Update

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