Melodia

Melodia

at Home

Cape Town

Member Since 7 Months Ago

Experience Points 9,170
Experience
Level
Lessons Completed 53
Lessons
Completed
Best Reply Awards 0
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

11 Dec
2 days ago

Melodia left a reply on How Can I Create A Folder For Each Registration On Amazon S3

@MTHOMAS - I see why one of my previous attempts didnt work. I had in a different structure.

Storage::disk('3')->put($file->getClientOriginalName(), fopen($file, 'r+'), 'public/' . $business->id )

Your code works on my storage. Am just going to check now if it also gets added to aws

How would I retrieve the image from a specific folder?

Say, I want to retrive the images from business id number 20

Melodia left a reply on How Can I Create A Folder For Each Registration On Amazon S3

@MTHOMAS - This creates the folder inside my public folder yes, but the files for that particular business are still being added outside that folder.

This is what I have now:

        $directory = 'public/' . $business->id;
        Storage::disk()->makeDirectory($directory);

        foreach($files as $file) {
            if ($file) {
                Storage::disk()->put($file->getClientOriginalName(), fopen($file, 'r+'));                   
            }
        }

Melodia started a new conversation How Can I Create A Folder For Each Registration On Amazon S3

I am using Amazon S3 to add files to it for my business registration system.

Inside the store method I have the following:

$input              = $request->all();

$files              = isset($input['file']) ? $input['file'] : array ();
$business_names     = json_decode($input['business_names'], true);
$business_details   = json_decode($input['business_details']);
$share_amount       = json_decode($input['share_amount'], true);
$entity             = json_decode($input['entity'], true);
$directors          = json_decode($input['directors'], true);
$shareholders       = json_decode($input['shareholders'], true);
$appointments       = json_decode($input['appointments'], true);

$input['user_id'] = Auth::user()->id;

Log::info(Auth::user());
Log::info($request->user());
/* Create Business Record */
$business = new Business;
$business->business_names = json_encode($business_names);
$business->share_amount = $share_amount ?: 0;
$business->entity = $entity ?: '';
$business->business_physical_address = json_encode($business_details->physical_address);
$business->has_business_postal_address = $business_details->has_postal_address;
$business->business_postal_address = json_encode($business_details->postal_address);
$business->user_id = $input['user_id'];
$business->save();

/* Upload Files */
foreach($files as $file) {
    if ($file) {
        Storage::disk()->put($file->getClientOriginalName(), fopen($file, 'r+'), 'public');
        // $file->storeAs('files/' . $business->id, $file->getClientOriginalName());
    }
} 

All works until now...but what I want something more organized, in a sense that, every time I save a new business, a folder is also created with that business id and the images should be added to that particular folder.

I tried this:

 Storage::disk('s3')->put($file->getClientOriginalName(), fopen($file, 'r+'), 'public/' . $business->id);

But I see the following error when I try to save a business:

#0 C:\xampp\htdocs\startingabandbaby\vendor\league\flysystem\src\Adapter\Local.php(356): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8, 'Undefined index...', 'C:\xampp\htdocs...', 356, Array)

Any way around that?

05 Dec
1 week ago

Melodia left a reply on Search Query Not Working With Min And Max Values

@d9705996 thinking of your last answer, I decided to alter my price data type to double, seeded some data and it seems like it works properly.

It happened that my price was a string type because I was using comma separation with javascript. Using double does not work.

Perhaps you would have an answer for that. Other than that we consider the question answered.

Melodia left a reply on Search Query Not Working With Min And Max Values

@D9705996 - I am soring price as a string.

Now I search the following:

https://mydomain.com/search?city_suburb=&type=&min_price=&max_price=2000000&bedrooms=&bathrooms=

I am expecting to view all properties which the price does not exceed 2000000...but the result shows me properties that cost 2600000, 20000000 and more.

In a different attempt I tried this:

https://mydomain.com/search?city_suburb=&type=&min_price=450000&max_price=&bedrooms=&bathrooms=

The results page show nothing...but I am expecting to see all properties which the price is equal or greater than 450000

Melodia left a reply on Search Query Not Working With Min And Max Values

@DANHORTON - If I follow your add-on logic, it still doesnt work.

For instance, I checked a property which min price is 1000000

http:/mydomain.com/search?city_suburb=&type=&min_price=1000000&max_price=&bedrooms=&bathrooms=

But the response shows me a properties which the price are even 500000 here is how my currently snippet looks like:

PropertyController.php

public function search_page(PropertyFilters $filters)
{
    $properties =  $this->getProperties($filters);

    return view('pages.search', compact('properties'));

} 

protected function getProperties(PropertyFilters $filters)
{
    $bids = Property::filter($filters);
    
    return $bids->paginate(9);
} 

PropertyFilters.php

protected $filters = ['city_suburb', 'type', 'min_price', 'max_price', 'bathrooms', 'bedrooms'];

public function city_suburb($city){
    if(!$city) {
       return $this->builder;
    } 
    return $this->builder->where('city', $city)->orWhere('suburb', $city);
}

public function type($type){
    if(!$type) {
       return $this->builder;
    } 
    return $this->builder->where('type', $type);
}

public function min_price($price){
    if(!$price) {
       return $this->builder;
    } 
    return $this->builder->where('price', '>=', $price);
}

 public function max_price($price){
    if(!$price) {
       return $this->builder;
    } 
    return $this->builder->where('price', '<=', $price);
}

public function bathrooms($bathrooms){
    if(!$bathrooms) {
       return $this->builder;
    }       
    return $this->builder->where('bathrooms', $bathrooms);
}

public function bedrooms($bedrooms){
    if(!$bedrooms) {
       return $this->builder;
    }       
    return $this->builder->where('bedrooms', $bedrooms);
}

Particularly for this line of code:

protected $filters = ['city_suburb', 'type', 'min_price', 'max_price', 'bathrooms', 'bedrooms'];

Why exactly do I have this array when I dont use the values? Because dont have min_price and max_price in the database.

Just trying to understand.

04 Dec
1 week ago

Melodia left a reply on Search Query Not Working With Min And Max Values

@D9705996 - nothing regarding the price works...whether I filter in isolation or with both min and max price.And note that if I do this:

public function min_price($price){
Log::debug($price);
if(!$price) {
   return $this->builder;
} 
return $this->builder->where('price', '>=', $price);
}

I get the price in my log

Melodia left a reply on Search Query Not Working With Min And Max Values

@DANHORTON - I do not quite follow the answer. what do I do with the protected filters array?

is it possible to have a full snippet based on mine?

Melodia left a reply on Search Query Not Working With Min And Max Values

@D9705996 - https://mydomain.com/search?city_suburb=&type=&min_price=1000000&max_price=&bedrooms=&bathrooms=

https://mydomain.com/search?city_suburb=&type=&min_price=&max_price=2000000&bedrooms=&bathrooms=

Melodia left a reply on Search Query Not Working With Min And Max Values

@D9705996 - https://owlcrest.co.za/search?city_suburb=&type=&min_price=1000000&max_price=&bedrooms=&bathrooms=

https://mydomain.com/search?city_suburb=&type=&min_price=&max_price=2000000&bedrooms=&bathrooms=

Melodia left a reply on How Can I Make A More Refine Search Result

@D9705996 - I was testing the search again and noticed that the min query for some reason does not work. I explain in more details in a new question and really hope you can help:

https://laracasts.com/discuss/channels/laravel/search-query-not-working-with-min-and-max-values

03 Dec
1 week ago

Melodia started a new conversation Search Query Not Working With Min And Max Values

I have form with multiple search input fields, which min and max values are included. When I try to search all properties which min price is 450 000 I see nothing, but in my database I have properties that are 2 000 000. Also on the same note, If put 1 000 000 as max value It shows me properties that are even 2 000 000.

My search function in the controller:

public function search_page(PropertyFilters $filters)
{
   $properties =  Property::filter($filters)->paginate(9);

   return view('pages.search', compact('properties'));
 
}   

PropertyFilters.php:

public function city_suburb($city){
    if(!$city) {
       return $this->builder;
    } 
    return $this->builder->where('city', $city)->orWhere('suburb', $city);
}

public function type($type){
    if(!$type) {
       return $this->builder;
    } 
    return $this->builder->where('type', $type);
}

public function min_price($price){
    if(!$price) {
       return $this->builder;
    } 
    return $this->builder->where('price', '>=', $price);
}

 public function max_price($price){
    if(!$price) {
       return $this->builder;
    } 
    return $this->builder->where('price', '<=', $price);
}

public function bathrooms($bathrooms){
    if(!$bathrooms) {
       return $this->builder;
    }       
    return $this->builder->where('bathrooms', $bathrooms);
}

public function bedrooms($bedrooms){
    if(!$bedrooms) {
       return $this->builder;
    }       
    return $this->builder->where('bedrooms', $bedrooms);
}

QueryFilter.php

abstract class QueryFilter
{
    protected $request;
    protected $builder;

    public function __construct(Request $request){
        $this->request = $request;
    }

    public function apply(Builder $builder){
        $this->builder = $builder;

        foreach($this->filters() as $name => $value){
            if($value && method_exists($this, $name)){
                call_user_func_array([$this, $name], array_filter([$value]));
            }
        }
        return $this->builder;
    }

    public function filters(){
        return $this->request->all();
    }
}

Anything possibly done wrong in the logic?

29 Nov
2 weeks ago

Melodia left a reply on Package Does Not Show On The Front-end

@LOSTDREAMER_NL - I jusr ran route,config and cache clear commands and everything works. I just found it weird that I had to clear anything since its just a small project and am not caching anything.

Appreciate the support

Melodia left a reply on Package Does Not Show On The Front-end

Route:list does not show anything and when I dd in both files nothing works. I ran composer dump-autoload and still nothing

28 Nov
2 weeks ago

Melodia left a reply on Package Does Not Show On The Front-end

@LOSTDREAMER_NL - I actually do have that line in my app.php under the providers array. Does not work. Says that page could not be found.

Melodia started a new conversation Package Does Not Show On The Front-end

I try to create a package but for some reason I cannot access the front-end. This is my package structure, from the project root directory:

/package/contact/src/routes/web.php /package/contact/composer.json /package/contact/ContactServiceProvider

The service provider class looks like the following:

namespace Sidneylab\Contact;

use Illuminate\Support\ServiceProvider;

class ContactServiceProvider extends ServiceProvider
{
    public function boot(){

        $this->loadRoutesFrom(__DIR__.'/routes/web.php');

    }

    public function register(){
    }
}

Compsoer.json

"name": "sidneylab/contact",
"description": "This will send email to admin and send contact query to database",
"type": "library",
"license": "MIT",
"authors": [
    {
        "name": "Sidney de Sousa",
        "email": "[email protected]"
    }
],
"minimum-stability": "dev",
"require": {},
"autoload": {
    "psr-4": {
        "Sidneylab\Contact\": "src/"
    }
},

web.php

Route::get('contact', function(){
return "contact";
 });

In my main composer.json file I added this:

"autoload-dev": {
    "psr-4": {
        "Tests\": "tests/",
        "Sidneylab\Contact\": "package/contact/src"
    }
},

Now, when I hit my url/contact it does not return anything. Anything I could have possibly missed?

14 Nov
4 weeks ago

Melodia left a reply on How To Check If Different Users Belong To The Same Community

@DANIELRUBANGO - Unfortunately this site does not follow certain laravel best practice approach and there is only so much I can do to change everything

Melodia left a reply on How To Check If Different Users Belong To The Same Community

Unfortunately, the site is a mess and doesn't follow best laravel conventions. However, I had the following idea.

I can get the community_id of the community_users table which I belong

$community_user_member = DB::table('community_users')->whereUserId($user->id)->pluck('community_id')->toArray();

Then I do the same for te user I want to see the posts:

$requested_user = DB::table('community_users')->whereUserId($user_id)->pluck('community_id')->toArray();

I initially an empty aray:

$common = [];

Then I try to use the in_array function to obtain an array with all the community_id

    foreach ($community_user_member as $key => $member) {
        if (in_array($member, $requested_user)) {
            $common[] = $member;

        }
    }
    print_r($common);

The end result should be something like this:

$common = [ '4','5','10','20' ];

Because then I would be able to loop through $common array and do whatever I want.

But I get the following error when I refresh the page:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
12 Nov
1 month ago

Melodia left a reply on How To Check If Different Users Belong To The Same Community

@DANIELRUBANGO - In general yes...but for this particular task am fetching the tables using DB.

Melodia started a new conversation How To Check If Different Users Belong To The Same Community

I have a table called communities, users, and community_users, and that table stores the user_id, as well as the community_id. Each user is or can be associated with multiple communities.

In this url, I pass a user_id

Route::get('/commoncommunityposts/{user_id?}', 'GolfPlayed\[email protected]');

The following is what I have in function for now which does not seem to make sense:

public function getCommonPostsByUser($user_id = null, Request $request)
{

    $user = $this->getAuthorizedUser($request->header('X-User-Auth-Token'));
    $user = User::find(22);
    if (!$user) {
        return response()->json(['error' => true, 'code' => 401, 'message' => INVALID_AUTH_TOKEN], 401);
    }

    $community_users = DB::table('community_users')->whereUserId($user->id)->get();

    foreach($community_users as $community){
        $check_user = DB::table('community_users')->whereUserId($user_id)->first(); 

        if(!empty($check_user)){
            return "You belong to the same community";
        }       
    }
}

I want to do whatever I need with the user that am fetching via url, as long as him and( $user->id) belong to the same community. How can I do that?

04 Nov
1 month ago

Melodia left a reply on My Post Method Not Working With Laravel-echo

Yes I do have an authenticated user. It's just the syntax in the vue side that is missing. I found typos but still wasnt all apparently:

export default {
    data(){
        return {
            project: {},
            newTask: ''
        }
    },
    created() {
        this.dataProject();        
    },
    methods: {

        save(){
            axios.post('/api/projects/${this.project.id}/tasks', {
                body: this.newTask
            })
            .then(response => response.data)
            .then(this.addTask);
        },
        addTask(task){
            this.project.tasks.push(task);

            this.newTask = '';
        },

        dataProject(){
            axios.get('/api/projects/${this.project.id}')
            .then(response => { 
                this.project = response.data;
                window.Echo.private('tasks. ' + this.project.id)
                    .listen('TaskCreated', ({task}) => this.addTask(task));
            });
        }
    }
}

It's unexpected token

app.js:53135 Uncaught SyntaxError: Unexpected token )

But I have no idea where else I should remove a bracket.

Melodia left a reply on My Post Method Not Working With Laravel-echo

I noticed that there was a missing brace, but still that didnt solve the issue and I see this error in the console:

 Uncaught Error: Module build failed: SyntaxError: C:/xampp/htdocs/laravel-echo/resources/assets/js/components/TaskList.vue: Unexpected token, expected , (43:8)

                  .listen('TaskCreated', ({task}) => this.addTask(task));

Melodia left a reply on My Post Method Not Working With Laravel-echo

@D9705996 I changed my script to this:

export default {
    data(){
        return {
            project: this.dataProject,
            newTask: ''
        }
    },
    created() {
        window.Echo.private('tasks. ' + this.project.id).
        listen('TaskCreated', ({task}) => this.addTask(task));
    },
    methods: {

        save(){
            axios.post('/api/projects/${this.project.id}/tasks', {
                body: this.newTask
            })
            .then(response => response.data)
            .then(this.addTask);
        },
        addTask(task){
            this.project.tasks.push(task);

            this.newTask = '';
        },

        dataProject(){
            axios.get('/api/projects/${this.project.id}')
            .then(response => { 
                this.project = response.data
            });
        }
    }
}

But still does work

Melodia left a reply on Pusher Notificiations Not Working

Aaaah yes. I had done that in one of the solutions attempt...had found it weird after running the queue worker because it was firing events as if it's an endless loop so I didnt really think that had saved the issue. Also interesting that I had tested the events on a fresh installation and never needed to run queue:work.

Melodia started a new conversation My Post Method Not Working With Laravel-echo

I was watching one of the tutorials for Laravel-echo but due to a very poor knowledge of vue.js I got lost along the way with private channels.

I created a projects and tasks table. All the relationship is created and below are my endpoints:

Route::get('/tasks', function(){
    return Task::latest()->pluck('body');
});

Route::get('/projects/{project}', function(Project $project){
    $project->load('tasks');
    return view('projects.show', compact('project'));
});

Route::get('/api/projects/{project}', function(Project $project){
    return $project->tasks->pluck('body');
});

Route::post('/api/projects/{project}/tasks', function(Project $project){
    $task = $project->tasks()->create(request(['body']));
    TaskCreated::dispatch($task);
    return $task;
});

Everything seems to be okay with my TaskCreated event:

public $task;

public function __construct($task)
{
    //
    $this->task = $task;
    $this->dontBroadcastToCurrentUser();
}

public function broadcastOn()
{
    return new PrivateChannel('tasks. ' .$this->task->project_id);// the id of the project
}

Now the issue comes in the vuejs:

<template>
    <div class="container">
        <ul>
            <li v-for="task in tasks" v-text="task"></li>
        </ul>
        <input type="text" v-model="newTask" @blur="addTask">
    </div>
</template>

<script>
    export default {
        data(){
            return {
                tasks: [],
                newTask: ''
            }
        },
        created() {
            axios.get('/tasks').then(response => (this.tasks = response.data));
            window.Echo.private('tasks. ' + this.project.id).listen('TaskCreated', e => {
                this.tasks.push(e.task.body);
            });
        },
        methods: {

            addTask(){
                axios.post('/api/projects/${this.project.id}/tasks', {
                    body: this.newTask
                })
                .then(response => {
                    this.showTasks();
                    this.newTask = '';
                })
            },
            showTasks(task){
                axios.get('/api/projects/${this.project.id}')
                .then(response => {
                    this.tasks = response.data.body
                })
            }
        }
    }
</script>

When I refresh the page on url/project/1 for example, I can see the task on that particular project. But if I enter another task and hit the tab key. Nothing happens.

Also I noticed the following error in the console when I refresh the page.

 Error in created hook: "TypeError: Cannot read property 'id' of undefined"

I want to be able to add a new task, and instantly have it updated in different browser where I have another user logged in.

Hope someone can help.

Thanks in advance

Melodia left a reply on Pusher Notificiations Not Working

I am not quite sure if it was cache, but suddenly everything works...pusher and log.

26 Oct
1 month ago

Melodia left a reply on Pusher Notificiations Not Working

This is how my controller looks like:

public function view_posts(){
    $user = User::find(6999);
    event(new TestNotification($user));
    return $user;       
}

And inside the TestNotification I initialized my constructor:

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class TestNotification implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $user;

    public function __construct($user)
    {
        $this->user = $user;
    }

    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

I changed the broadcast_driver to log. When refresh the url, I get the user, but nothing is added to my log.

25 Oct
1 month ago

Melodia left a reply on Pusher Notificiations Not Working

Thanks for the tip on the .env

Point is, regardless of broadcasting, when I call the event, I should be able to see something on pusher console area about that particular event. But for some reason I dont see anything.

if I call a post funtion

$post = Post::create($request->all());

PostNotification::dispatch($post);

$post variable would become public inside PostNotification event. When I create a new post, pusher should be able to show me the post that was just created.

Melodia left a reply on Pusher Notificiations Not Working

@D9705996 no need to worry about the .env. Those are just dummy content. Regarding the tutorial recommendation, thanks. However, the second tutorial would be what I would like to watch, because the problem is when I try to push to pusher.

my .env files were configured the same Jeffrey configured at Laracasts tutorial.

Hope someone can help.

24 Oct
1 month ago

Melodia started a new conversation Pusher Notificiations Not Working

I have function that adds people into a chat a group. That works. All I need to do now, is create an event that send a notification to each member that was added, that they were just added.

The method looks like this:

public function addGroupChatMember(Request $request, $id) {
    $user = $this->getAuthorizedUser($request->header('X-User-Auth-Token'));

    if (!$user) {
        return response()->json(['error' => true, 'code' => 401, 'message' => INVALID_AUTH_TOKEN], 401);
    }

    $validator = Validator::make($request->all(), [
        'user_ids' => 'required|array|min:1',
    ]);



    if ($validator->fails()) {
        return response()->json(['error' => true, 'code' => 400, 'message' => $validator->errors()]);
    }
    Connect::setAuthUserId($user->id);

    if ($participants = Connect::addConversationMember($id, $request->get('user_ids'))) {

        if(is_array($request->user_ids)){
            foreach($request->user_ids as $uId){
                event(new SendGroupChatMember($participants, $uId));    
            }               
        }
        else{
            event(new SendGroupChatMember($participants, $request->user_ids));  
        }

        return response()->json(['status' => 'success', 'message' => 'Add new member successfully', 'participants' => $participants], 200);
    }

    return response()->json(['error' => true, 'code' => 400, 'message' => 'Unable to add member to conversation']);
}

My SendGroupChatMember.php looks like this:

public $uId;
public $participants;

public function __construct($participants, int $uId = 0 )
{
    $this->uId = $uId;
    $this->participants = $participants;
}

public function broadcastAs()
{
    return 'new-group-chat-receive-event';
}

public function broadcastOn()
{
    $channel = 'golfplayed-new-group-chat';
    if(!empty($this->uId)) {
        $channel .= '-' . $this->uId;
    }
    return new Channel($channel);
}

For some reason, when I make the request, the event does not work. When I go to pusher console, I do not see anything about the even.

I followed the documentation on how to use pusher and everything is configured in .env file.

BROADCAST_DRIVER=pusher

PUSHER_APP_NAME=thename
PUSHER_APP_ID=262815
PUSHER_APP_KEY=3461161115151515a2e1
PUSHER_APP_SECRET=a24e8dd95b0aa14dvvdfvdd
PUSHER_APP_CLUSTER=us2

Is there anything else I need to do for pusher to work?

Melodia left a reply on Cannot Serialize Or Unserialize PDO Instances On Get Request

I actually just realized that if I dd($community), I do receive the community result.

However, If dd($post), I do receive a result

Melodia started a new conversation Cannot Serialize Or Unserialize PDO Instances On Get Request

For my api's, I want to notify the owner of a community everytime a comment is posted in a post that belongs to his community and my code looks like this, and the function looks like this:

public function communityPostComment(Request $request, $post_id) {
    $user = $this->getAuthorizedUser($request->header('X-User-Auth-Token'));
    $user = User::find(6999);
    if (!$user) {
        return response()->json(['error' => true, 'code' => 401, 'message' => INVALID_AUTH_TOKEN], 401);
    }

    //$text = $request->input('comment_text');
    $text = "This is my latest";

    if (is_null($text) || $text == '') {
        return response()->json(['error' => true, 'code' => 400, 'message' => 'No comment text submitted']);
    }

    try {
        if(0 && \App::environment('production-trigger')) {
            $insert = \DB::connection('trigger')->table('tbl_Community_Post_Comments')->insertGetId([
                'User_ID' => $user->id,
                'Post_ID' => $post_id,
                'Comment_Text' => $text,
                'Created_Date_Time' => Carbon::now()->format('Y-m-d H:i:s'),
                'Active' => 1,
            ]);
            $post = \DB::table('community_custom_posts')->wherePostId($post_id)->first();
            $community = Community::whereUserId($post->community_id);
            event(new SendPostCommentNotification($community, $user));

        } else {
            $insert = CommunityPostComment::insertGetId([
                'post_id' => $post_id,
                'user_id' => $user->id,
                'comment_text' => $text,
                'active' => 1,
                'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
            ]);
            $post = \DB::table('community_custom_posts')->wherePostId($post_id)->first();
            $community = Community::whereUserId($post->community_id)->get();
            event(new SendPostCommentNotification($community, $user));




        }
        return response()->json(['success' => true, 'code' => 200, 'comment_id' => $insert]);
    } catch (\PDOException $e) {
        return response()->json(['error' => true, 'code' => 400, 'message' => 'Unsuccessful comment attempt', 'error_message' => $e->getMessage()]);
    }
}

This is how my route looks like:

Route::get('post/comment/{post_id}', 'GolfPlayed\[email protected]')->where('post_id', '[0-9A-Za-z\-]+')->name('api.communityPostComment');

When I type this:

http://productionapi.local/post/comment/613

I get this in my response:

error_message   "You cannot serialize or unserialize PDO instances"

I have the feeling that the error is in this line:

$community = Community::whereUserId($post->community_id);

If I do dd($community) I a result though.

If I do this:

$community = Community::whereUserId($post->community_id)->get();

I dont receive anything.

Anything I am possibly doing the wrong way?

21 Oct
1 month ago

Melodia left a reply on Schedule Command Not Working

This actually works. I guess I just had a to wait a few minutes after I pushed the changes to the server.

Melodia started a new conversation Schedule Command Not Working

I created a new command named: DeleteOfferCommand and it looks like this:

class DeleteOfferCommand extends Command
{

    protected $signature = 'app:delete-offer';

    protected $description = 'Delete expired offers';

    public function handle()
    {
        $offers = Offer::all();

        foreach($offers as $offer){

            if(now() >= $offer->expires_at){    
                $offer->delete();
            }
        }
    }
}

In the tutorial, I see that there is a folder called start which I should use to intiate the command:

Artisan::add(new DeleteOfferCommand);

However, I do not see that folder on my side, also checked laravel documentation and didnt see that instruction.

Moving on, I went to my forge account and created a new schedule which looks like the following:

php /home/forge/mysite.com/artisan app:delete-offer

If I ssh into the server and run the artisan command, I am able to see the command.

app:delete-offer     Delete expired offers

But when I go to my site, I do not see any effect.

The offer expired about an hour ago but It wasnt delete.

Anything I need to add to make my code work?

13 Oct
2 months ago

Melodia left a reply on How Can I Make A More Refine Search Result

@D9705996 I followed your suggestion and it actually works now. Initialized all the variables and put a conditional statement in all the methods.

public function city_suburb($city = null){
    if(!$city) {
       return $this->builder;
    } 
    return $this->builder->where('city', $city)->orWhere('suburb', $city);
}

public function type($type = null){
    if(!$type) {
       return $this->builder;
    } 
    return $this->builder->where('type', $type);
}

public function min_price($price = 0){
    if(!$price) {
       return $this->builder;
    } 
    return $this->builder->where('price', '>=', $price);
}

 public function max_price($price = 0){
    if(!$price) {
       return $this->builder;
    } 
    return $this->builder->where('price', '<=', $price);
}

public function bathrooms($bathrooms = null){
    if(!$bathrooms) {
       return $this->builder;
    }       
    return $this->builder->where('bathrooms', $bathrooms);
}

public function bedrooms($bedrooms = null){
    if(!$bedrooms) {
       return $this->builder;
    }       
    return $this->builder->where('bedrooms', $bedrooms);
}

Melodia left a reply on How Can I Make A More Refine Search Result

Sounds a bit odd. I attempted to initialise the price to zero, but it complained about the other methods. So intialized everything to null. But now if I just search for type, it gives me an empty array.

public function type($type){
    return $this->builder->where('type', $type);
}

public function min_price($price = 0){
    return $this->builder->where('price', '>=', $price);
}

public function max_price($price = 0){
    return $this->builder->where('price', '<=', $price);
}

public function bathrooms($bathrooms = null){
    return $this->builder->where('bathrooms', $bathrooms);
}

public function bedrooms($bedrooms = null){
    return $this->builder->where('bedrooms', $bedrooms);
}

Melodia left a reply on How Can I Make A More Refine Search Result

I remember to have changed to that but it did not work. But I followed Jeffrey's tutorial and just trying to implement the way he explained.

All works, but only if I type the query in the url my self. If I user the form, it gives me this error:

 Too few arguments to function App\PropertyFilters::min_price(), 0 passed and exactly 1 expected

And the url converts into these:

http://owlcrest.local/search?city_suburb=&type=apartment&min_price=&max_price=&bedrooms=&bathrooms=

Which seems like all records are compulsory

My form looks like this:

{!! Form::open(['method' => 'GET', 'action'=>'[email protected]_page']) !!}
    <div class="row flex wrap">

        <div class="col-sm-10">
            <div class="search-input">
                {!! Form::text('city_suburb', null, ['class'=>'form-controla', 'placeholder'=>'Search for suburb']) !!}         
            </div>

            <div class="select-boxes">
                {!! Form::select('type', [''=>'Type of property'] + ['apartment'=>'Apartment', 'house'=>'House', 'plot'=>'Plot', 'smallholding'=>'Smallholding', 'commercial'=>'Commercial', 'townhouse'=>'Townhouse'], null, ['class'=>'form-']) !!}   

                {!! Form::select('min_price', [''=>'Minimum'] + [450000 => 'R 450 000', 5000000 => 'R 500 000', 1000000 => 'R 1 000 000',2000000 => 'R 2 000 000', 3000000 => 'R 3 000 000', 4000000 => 'R 4 000 000',5000000 => 'R 5 000 000', 6000000 => 'R 6 000 000',

], null, ['class'=>'form-']) !!} {!! Form::select('max_price', [''=>'Maximum'] + [450000 => 'R 450 000', 500000 => 'R 500 000', 1000000 => 'R 1 000 000',2000000 => 'R 2 000 000', 3000000 => 'R 3 000 000', 4000000 => 'R 4 000 000',5000000 => 'R 5 000 000', 6000000 => 'R 6 000 000', ], null, ['class'=>'form-']) !!} {!! Form::select('bedrooms', [''=>'Bedroom'] + [2=>'1+', 3=>'2+', 20=>'20+'], null, ['class'=>'form-']) !!} {!! Form::select('bathrooms', [''=>'bathroom'] + [2=>'1+', 3=>'2+', 20=>'20+'], null, ['class'=>'form-']) !!}

        <div class="col-sm-2">
            {!! Form::submit('Search', ['class'=>'search bg-brown']) !!}
            <button class="clear-filter button">Clear Filter</button>
        </div>                  
    </div>

{!! Form::close() !!}

My function in the search_page became like the one below:

public function search_page(PropertyFilters $filters)
{
   return Property::filter($filters)->get();
 
} 

PropertyFilters.php

class PropertyFilters extends QueryFilter
{

    public function type($type){
        return $this->builder->where('type', $type);
    }

    public function min_price($price){
        return $this->builder->where('price', '>=', $price);
    }

    public function max_price($price){
        return $this->builder->where('price', '<=', $price);
    }

    public function bathrooms($bathrooms){
        return $this->builder->where('bathrooms', $bathrooms);
    }

    public function bedrooms($bedrooms){
        return $this->builder->where('bedrooms', $bedrooms);
    }
}

QueryFilter.php

abstract class QueryFilter
{
    //
    protected $request;
    protected $builder;

    public function __construct(Request $request){
        $this->request = $request;
    }

    public function apply(Builder $builder){
        $this->builder = $builder;

        foreach($this->filters() as $name => $value){
            if(method_exists($this, $name)){
                call_user_func_array([$this, $name], array_filter([$value]));
            }
        }

        return $this->builder;
    }

    public function filters(){
        return $this->request->all();
    }
}

I guess this goes back to the question @Snapey asked previously: When a user enters different searches, are you wanting them to be AND (the reply must contain all the search terms) or OR (the reply contains any of the search terms).

So in this case the reply should only contain the the search terms.

Melodia left a reply on How Can I Make A More Refine Search Result

@D9705996 Yes I watched the tutorial and my code is based on the first minutes of that tutorial if you take a look at that. But it feels weird to follow the advanced when the basic is not working.

Melodia left a reply on How Can I Make A More Refine Search Result

The second url gives a result.

But now if I just type this:

http://owlcrest.local/search?max_price=200

It does not show valid data. I see properties that price are higher than 200

Melodia left a reply on How Can I Make A More Refine Search Result

So, I now changed my method to this:

public function search_page(Request $request)
{
    $property = (new Property)->newQuery();
   
    if($request->exists('suburb')){
        $property->whereSuburb($request->suburb);
    }

    if($request->has('max_price')){
        $property->where('price', '<=', $request->max_price);
    }

    return $property->get();
 
}  

But this is what happens: The below works:

http://owlcrest.local/search?suburb=Kenilworth

But the below does not really work:

http://owlcrest.local/search?max_price=200

It returns me properties which the price are even 1554511

And if I search for this:

http://owlcrest.local/search?suburb=Kenilworth?max_price=52954

It does not return anything, which is not really right.

Melodia left a reply on How Can I Make A More Refine Search Result

@Snapey I just changed my search:

  http://owlcrest.local/search?suburb=Kenilworth

But it still return all the properties from the table instead.

"When a user enters different searches, are you wanting them to be AND (the reply must contain all the search terms) or OR (the reply contains any of the search terms)."

The reply must contain any of the search term. Because I could search for a property by city only. Or could search property by city where min price is 200000dollars. Or I can just search for property by min price, and etc. Hope I managed to explain properly

"I don't know how you are sending kenilworth but it shouldn't have quotes around it? (those %22's)"

At the moment I am entering the url manually, just fo rtesting purposes.

Melodia started a new conversation How Can I Make A More Refine Search Result

I am learning query strings and have an input form with multiple entries for search. One of them is max_price ad suburb.

When I search for all properties in Kenilworth, I see that the filter does not work because it shows me all the properties.

http://owlcrest.local/search?suburb=%22Kenilworth%22

At the moment this is what I have in my controller:

public function search_page(Request $request)
{
    $property = (new Property)->newQuery();
   
    if($request->exists('suburb')){
        $property->orderBy('id', 'desc');
    }

    if($request->has('max_price')){
        $property->where('price', '<=', $request->max_price);
    }

    return $property->get();
 
}

The route looks like this:

Route::get('/search', '[email protected]_page')->name('search-page');

So, I want to implement a search that handles all type of requests. A user should be capable of searching with max_price only, min_price, suburb, or all.

How can I go about that?

My function initially looked like the one below, and I had posted a question about that before, but it didnt give me correct results

public function search_page(Request $request)
{
    // validation ...
    $query = Property::query();

    if ($city = $request->input('city_suburb') ?? '')
    {
        $query->where('city', $city)
              ->orWhere('suburb', $city);
    }

    if ($type = $request->input('type') ?? '')
    {
        $query->where('type', $type);
    }

    // if none of them is null
    if (! (is_null($request->input('min_price')) && is_null($request->input('max_price')))) {
        // fetch all between min & max values
        $query->whereBetween('price', [$request->input('min_price'), $request->input('max_price')]);
    }
    // if just min_price is available (is not null)
    elseif (! is_null($request->input('min_price'))) {
        // fetch all greater than or equal to min_price
        $query->where('price', '>=', $request->input('min_price'));
    }
    // if just max_value is available (is not null)
    elseif (! is_null($request->input('max_price'))) {
        // fetch all lesser than or equal to max_value
        $query->where('price', '<=', $request->input('max_price'));
    }

    $properties = $query->orderBy('id', 'asc')->paginate(9);

    return view('pages.search', compact('properties'));     
}

Hope that someone can support on that.

12 Oct
2 months ago

Melodia left a reply on Quick Deploy Not Working

I followed your instructions. Pasted the payload url in my new webhook, but noticed that it was deploying forever..like an endless loop

11 Oct
2 months ago

Melodia left a reply on Quick Deploy Not Working

@shez1983 IS there a specific name for the Payload url?

10 Oct
2 months ago

Melodia started a new conversation Mail Queue Does Not Work

I have a table for properties and for users. Everytime I change the status of a property to 1, I want to notify the user about the action. Initially it was working with the normal email, but now that I added queue, when I click to change status, the page refreshes but nothing happens.

This is how my method looks in the controller:

public function activate($id) {
    $property = Property::whereId($id)->first();
    $property->update(['status'=> 1]);
    Mail::queue(new PropertyActive($property));
    return redirect()->back();
}

The mailable:

public $property;
public function __construct($property) {

    $this->property = $property;
    $this->to($property->user->email, 'Owlcrest');
    $this->subject('Your property listing');
}

I first tried with ShouldQueue in the mailable but that didnt really work either.

I had noticed that my queue driver was still set to sync change to database:

QUEUE_DRIVER=database

Melodia left a reply on SQLSTATE[HY000] [2002] When Trying A Simple Get() Over A Table

@stratboy One thing that I noticed is that you use the get method:

$associates = DB::table('associates'); dd($associates->get());

Ideally you should use all() because there is no where clause.

Do you see your associates table if you check your database? If you maybe delete all your tables including migrations, run this in your terminal.

composer dump-autoload 

And then

php artisan migrate

Also, and not that it should matter, is there a reason why you're not using eloquent?

09 Oct
2 months ago

Melodia left a reply on Quick Deploy Not Working

@Cronix I actually deployed the site using this tutoral. It says that to enable quick deploy you just have to click under "enable quick deploy" and it should work. Actually the having to create a web hook was an answer given by someone from forge, but I just dont see that option in my github account.

Melodia left a reply on Quick Deploy Not Working

When I click on quick deploy it works, but the same does not happen if I try to enable quick deploy. I read that I have to create a web hook on my github account.I must go to settings, developer settings and add webhook. But it happens that I do not see the option to Add a hook on my side

08 Oct
2 months ago

Melodia started a new conversation Quick Deploy Not Working

I have a site running for a couple of days already and I noticed that my quick deploy never worked. Even though I clicked to enable quick deploy, I still have to manually deploy it.

Is there anything else that I need to configure for that to work?