almost_pitt

almost_pitt

Member Since 2 Years Ago

Web Developer at Freelance

Experience Points 29,780
Experience Level 6

220 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 285
Lessons
Completed
Best Reply Awards 0
Best Reply
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.

15 May
4 days ago

almost_pitt left a reply on Old Input File Laravel

If it's a PDF or text file, you can convert it into base64 and then save the old input. Otherwise, as @snapey says, you cannot repopulate a file element for security reasons.

01 Sep
8 months ago

almost_pitt left a reply on Bootstrap Not Loading

The glyphicons aren't available in bootstrap 4. That's probably the reason.

22 Jul
9 months ago

almost_pitt left a reply on Passing Data Through Return Redirect Back To Update Request

Thanks for your help @Jawelo! Your answer was spot on and helped push me in the right direction!

Here is how I solved the whole puzzle:

I had to correct myself in how I pushed the $email through to the view:

LeadsController

return redirect()
    ->back()
    ->with('message','sign up')
    ->withInput($request->all)
    ->with('email', $request->get('email'));

Notice how I'm sending the email through as 'email' here, just as @Jawelo said ;)

Then, I pushed the email through the view in the 2nd form like this:

index

<form method="post" action="{{ route('leads.update', session('email')) }}">

Then, finally, in order to capture the email again, use it to find the lead that I wanted, I had to drastically change the update:

public function update($email) { DB::table('my_renamed_table') ->where('email', $email) ->update(['newsletter' => Input::get('newsletter')]); return redirect()->back()->with('success','success'); } Thanks again!

almost_pitt started a new conversation Passing Data Through Return Redirect Back To Update Request

Hey guys,

I am trying to allow a user to update their information after they have submitted a form, but did not check a certain box. Everything is within the same page and I am controlling the different modals by returning a message, which triggers a script to open the different modals.

For some reason, I can't seem to pass the ID or email through to the next step. Can anyone help with this?

Whenever, I try, I get the following error:

Undefined variable: leads 

Any idea?

Thanks!!!

Files:

web.php index.blade.php LeadsController.php Leads.php

Web.php

...
Route::post('/', [
    'uses' => '[email protected]',
    'as' => 'leads.store'
]);
Route::patch('/{email}', [
    'uses' => '[email protected]',
    'as' => 'leads.update'
]);
...

Index.blade.php

<html>
<div id="contact" class="modal fade">
    <div class="modal-dialog modal-content modal-lg">
        <div class="modal-body">
            <form id="form" class="form" action="/" method="post" accept-charset="utf-8">
                {{ csrf_field() }}
                <input type="email" name="email" value="{{ old('email') }}">
                <input type="checkbox" name="newsletter">
                <button type="submit">Submit</button>
            </form>
        </div>
    </div>
</div>

@if(session()->has('message'))
    <div id="sign_up" class="modal fade">
        <div class="modal-dialog modal-content modal-lg">
            <div class="modal-body">
                <form method="post" action="{{ route('leads.update', $leads->email) }}">
                     {{ csrf_field() }}
                     {{ method_field('PATCH') }}
                     <input type="checkbox" name="newsletter">
                     <button type="submit">Submit</button>
                </form>
            </div>
        </div>
    </div>
@endif

</body>

</html>
public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'email'        => 'required|email',
    ]);
    if ($validator->fails()) {
        return redirect()->back()->withErrors($validator)->withInput($request->all);
    } else {
        try {
            $leads = new Leads;
            $leads->email        = $request->email;
            $leads->newsletter   = $request->newsletter;
            $leads->save();
            if($request->newsletter == ''){
                return redirect()->back()->with('message','sign up')->withInput($request->all)->with($leads->email, $request->get('email'));
            }
            if($request->newsletter == 'true'){
                return redirect()->back()->with('success','success');
            }
        } catch (Exception $e) {
            return response()->json(
                [
                    'status' => false,
                    'error' => base64_encode($e->getMessage()),
                ],
                Status::HTTP_INTERNAL_SERVER_ERROR
            );
        }
    }
}

public function update($email)
{
    $leads = Leads::find($email);
    $leads->newsletter = $input('newsletter');
    $leads->save();
    return redirect()->back()->with('success','success');
}

Leads.php

21 Dec
1 year ago

almost_pitt started a new conversation Validation - Takes 50-60 Seconds To Reload - Any Ideas How To Improve This?

Hey guys,

I have a form that uses validation. Imagine that a user forgets to put in a line and the page returns back with errors and with input.

In this case, the page takes 53.58 seconds to load (on this occassion). The main culprits are:

  • ng-validate.js - 49.69 seconds
  • ng-inspector.js - 49.42 seconds.

I have tried to add browser caching to my .htaccess file in the root folder. However, this hasn't improved the speeds.

Is there any other way to improve the load speed for form validation when it reloads? Is there something that I am maybe missing? All thoughts, ideas, and criticism are welcome. :)

(By the way, the page itself takes 3 seconds to load on a fresh load when not being returning back with input or errors.)

Thanks!

Brad

almost_pitt left a reply on Complex Conditional Validation - Not Working :(

I have figured it out!

Don't forget this:

if($validator->fails()){
  return back()
  ->withinput()
  ->withErrors($validator);
}

Thanks to this page on Stackoverflow: https://stackoverflow.com/questions/43812067/laravel-5-4-complex-conditional-validation

19 Dec
1 year ago

almost_pitt started a new conversation Complex Conditional Validation - Not Working :(

Hey guys,

I'm trying to use complex conditional validation for my form. In it, I would like for the field Furnished_2 to be required if Number_of_Bedrooms is set to 2 or more and Renting_Entire_Property is set to Renting_Entire_Property.

Here is my first attempt using required_if.

'Furnished_2' => 'required_if:Renting_Entire_Property,Renting_Entire_Property|required_if:Number_of_Bedrooms,>=,2',

Apparently, you can only use 1 required_if statement at a time. So, this didn't work.

Then, I tried Complex Conditional Validation as outlined here: https://laravel.com/docs/5.4/validation, although I am a bit uncertain of how it actually works.

Here is how my validation works:

    public function store(Request $request)
    {
        $this->validate(request(), [
            'Title' => 'required|max:45|min:10',
            'Type_of_Property' => 'required',
            'Floor_Level' => 'required',
            'Elevator' => 'required',
            'Number_of_Bedrooms' => 'required',
            'Number_of_Bathrooms' => 'required',
            'Furnished' => 'required',

            'Number_of_Beds_1' => 'required',
            'Type_of_Beds_1_1' => 'required',
            'Furnished_1' => 'required',
            'Number_of_Guests_1' => 'required',

            'Security_Deposit' => 'required_if:Security_Deposit_Check,==,Security_Deposit_Check',

            'Landlords_Comments_1' => 'max:280',
            'Landlords_Comments_2' => 'max:280',

            'formatted_address' => 'required|min:10',
            'locality' => 'required',

            'price' => 'required|integer|between:100,9999',
            'datepicker' => 'required',
            'Minimum_Rental_Period' => 'required',
        ]);

Then, I'm not really sure how to insert the validator. I tried to insert it after this. Such as:

        $v = Validator::make($data, [
        ...static validation here...
        ]);

        $v->sometimes('Furnished_2', 'required', function ($input) {
            return $input->Number_of_Bedrooms >= 2;
            return $input->Renting_Entire_Property >= 'Renting_Entire_Property';
        });

and I inserted use Validator; at the top. Unfortunately, I keep running into errors.

Any idea how to complete the Complex Conditional Validation?

Thanks!

15 Dec
1 year ago

almost_pitt left a reply on Required_if Not Working

So, I realized that something in my jQuery was preventing this.

This actually works:

            'Number_of_Bedrooms' => 'required',

            'Furnished_2' => 'required_if:Number_of_Bedrooms,==,2',
```
Here is my jQuery:

```
      $("#submit").on("click",function(){
        var formatted_address = $('input#formatted_address').val();
        var latitude = $('#latitude').val();
          if(latitude == ""){
            $('html,body').animate({scrollTop: $("#formatted_address").offset().top - 100});
            $("form").submit(function(e){e.preventDefault();});
          } else {
            $("form").unbind('submit').submit()
          }
      });
      $("input#formatted_address").on("change",function(){
            var formatted_address = $('input#formatted_address').val();
            if(formatted_address !== ""){
                $("#address_required").addClass("d-none");
            }
            if(formatted_address == ""){
                $("#address_required").removeClass("d-none");
            }
      });
      $(window).scroll(function() {
          var scroll = $(window).scrollTop();
          var offset = $('#formatted_address').offset().top;
          var formatted_address = $('input#formatted_address').val();
              if(formatted_address == ""){
                if (scroll >= offset - 250 ) {
                    $("#address_required").removeClass("d-none");
                  }
              }
        });

```

almost_pitt left a reply on Required_if Not Working

Thanks @Saikishore . Unfortunately, it didn't work. Do you think that it's a problem that I have this within the:

    public function store(Request $request)
    {
        $this->validate(request(), [
        ]);
    }

almost_pitt started a new conversation Required_if Not Working

Hey guys,

Inside of my controller, I would like to require certain inputs if something is chosen.

For example, if the number of bedrooms is 2 or more, I would like the Furnished input for bedroom 2 to be required.

Here is the code that I have tried inside of my RoomsController.php:

            'Number_of_Bedrooms' => 'required',

            'Furnished_2' => 'required_if:Number_of_Bedrooms,2',

I have also tried,

            'Number_of_Bedrooms' => 'required',

            'Furnished_2' => 'required_if:Number_of_Bedrooms,==,2',

Note: Number_of_Bedrooms is a select input and the values go from 'Studio' to '1' to '6'

This, unfortunately, does not seem to wrok. I've looked at the documentation https://laravel.com/docs/5.4/validation#rule-required-if, but haven't been able to figure it out.

Can anyone help?

Thanks!

29 Nov
1 year ago

almost_pitt left a reply on Failed To Authenticate On SMTP Server With Username "[email protected]" Using 2 Possible Authenticators

Hi @ejdelmonico ,

Thanks for your quick reply.

I think you mean "Allow less secure apps." If so, mine is on. https://myaccount.google.com/lesssecureapps

Hmm... is there no way to solve this outside of Mailgun?

almost_pitt started a new conversation Failed To Authenticate On SMTP Server With Username "[email protected]" Using 2 Possible Authenticators

Hey guys,

I have an application that sends out emails. Everything was working fine until I connected this email address to my Gmail account in order to have easier access to it and to be able to reply to users.

Now I'm getting an error on the site:

(1/1) Swift_TransportException

Failed to authenticate on SMTP server with username "[email protected]" using 2 possible authenticators.

I have tried the following to fix this problem:

⋅⋅* I have checked all of the mail settings and they are all correct.

MAIL_DRIVER=smtp
MAIL_HOST=mydoma.in
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=mysupersecretpassword
MAIL_ENCRYPTION=ssl

⋅⋅* I have SSHed in and tried clearing the cache:

php artisan config:cache
php artisan config:clear

⋅⋅* I have gone to: https://myaccount.google.com/security#connectedapps and ensured that "Allow less secure apps: ON"

⋅⋅* I have gone to: https://accounts.google.com/UnlockCaptcha, clicked continue, and unlocked my account for access through other media/sites

Any idea what else it could be?

Thanks guys!

23 Nov
1 year ago

almost_pitt left a reply on Submit Form Within Bootstrap Modal - TokenMismatchException Error

@matt_panton , hmmm, that's weird. I still couldn't get it to work. It looks like our code is the same. Are you doing this within a bootstrap modal?

almost_pitt left a reply on Submit Form Within Bootstrap Modal - TokenMismatchException Error

@Cronix , actually the form won't submit without the Javascript here since it is in a Bootstrap Modal.

almost_pitt left a reply on Submit Form Within Bootstrap Modal - TokenMismatchException Error

Good idea @matt_panton, but unfortunately, then it doesn't submit anything at all. :(

almost_pitt left a reply on Submit Form Within Bootstrap Modal - TokenMismatchException Error

Good catch @matt_panton -> This, unfortunately, was just my typo for the code I am pasting here.

almost_pitt started a new conversation Submit Form Within Bootstrap Modal - TokenMismatchException Error

Hey guys,

I'm creating a form inside of a bootstrap modal. Here is the form:

´´´

{{ csrf_field() }} Submit

´´´

and here is the javascript I'm using to post it:

´´´

function form_submit() { document.getElementById("facebook_form").submit(); } ´´´

Unfortunately, when I submit, I get the following error:

(1/1) TokenMismatchException in VerifyCsrfToken.php (line 68)

I've also tried to insert a hidden field for the token:

<input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" />

Unfortunately, no luck.

Any idea how I can fix this?

Thanks!

07 Oct
1 year ago

almost_pitt left a reply on Delete All Photos Within A Project When You Delete The Project

Amazing! Thanks @ftrillo

This:

Photo::destroy(Photo::where('room_id', $id)->pluck('id')->all());

worked!

For some reason, the onDelete('cascade') didn't work. But, I'll keep looking at that to see if I can figure out why.

Thanks again @ftrillo !!!

almost_pitt left a reply on Delete All Photos Within A Project When You Delete The Project

@ftrillo

Is this what you mean by your ON DELETE CASCADE comment?

create_photos_table.php

    public function up()
    {
        Schema::create('photos', function (Blueprint $table) {
            $table->increments('id');

            $table->integer('room_id')->unsigned();
            $table->foreign('room_id')->references('id')->on('rooms')->onDelete('cascade');

            $table->string('name');
            $table->string('path');
            $table->string('thumbnail_path');
            $table->timestamps();
        });
    }

almost_pitt left a reply on Delete All Photos Within A Project When You Delete The Project

Wow! @ftrillo Thanks so much for the thorough explanation!

I have one last question.

I'm pushing all of the pictures to my local computer. Now, when I delete the Room, the images disappear from the list of images in MySQL. However, they still remain in the photos folder on my computer.

But, when I delete the images one by one within the Room, they delete from my computer.

Any idea why this could be happening and how I could delete these images from the folder as well?

Thanks!!

almost_pitt started a new conversation Delete All Photos Within A Project When You Delete The Project

Hey guys,

I've built something similar to Project Flyer. I would like to be able to delete all of the images that I have uploaded to one flyer whenever I delete that flyer. (In my case, these flyers are rooms.)

In my RoomsController, I have the following function for deleting a room.

    public function destroy($id)
    {
        Room::destroy($id);

        Session::flash('success', 'Room deleted successfully.');

        return redirect()->back();
    }

This deletes the room, but it doesn't delete any of the photos associated with that room.

In my create photos table, I call in the "room_id" as well so that I can link the two. Therefore, my idea was the following:

    public function destroy($id)
    {
        Room::destroy($id);

        $photos = Photo::all()->where('room_id', $id);
        $photos->destroy();

        Session::flash('success', 'Room deleted successfully.');

        return redirect()->back();
    }

However, when I run this code, I always get the error message: 1/1) BadMethodCallException Method destroy does not exist.

Do you guys have any idea how I could do this?

When I call

dd(Photo::all()->where('room_id', $id));

Then, it gives me the correct list of images associated with the room. So, that works. It's just the deleting part that's not quite there yet.

Thanks for any and all suggestions, ideas, and input!! :)

14 Sep
1 year ago

almost_pitt left a reply on Pass A Variable Into A Data Array To Send Email

@Snapey -> Think this would leave it open for security concerns?

Thanks for the foresight!

almost_pitt left a reply on Pass A Variable Into A Data Array To Send Email

Okay, okay, how about this @Snapey , @bashy

Now, I'll pass the user's ID through the form and then find that ID again in the sendEmail function so that I can hide the email in the HTML, but then link it back to the ID in the function.

What do you think about that?

Form

``` {{ csrf_field() }} ... ... ```

PostsController.php

``` public function sendEmail(Request $request, Post $posts) { $landlordsemail = Post::all()->where('user_id', $request->landlordsid )->pluck('user_email')->first(); $this->validate($request, [ 'email' => 'required|email', 'subject' => 'min:3', 'message' => 'min:10' ]); $data = array( 'email' => $request->email, 'subject' => $request->subject, 'bodyMessage' => $request->message, 'landlordsemail' => $landlordsemail ); Mail::send('emails.contact', $data, function($message) use ($data){ $message->from($data['email']); $message->to( $data['landlordsemail'] ); $message->subject($data['subject']); });
    Session::flash('success', 'Your email was sent.');

    return redirect()->route('home');
}

almost_pitt left a reply on Pass A Variable Into A Data Array To Send Email

Guys, I finally figured out a way around this problem! Perhaps it's not the most direct, but here it is:

I simply pass the {{$posts->user_email}} into a hidden input in the form and then retrieve it through the data array.

Like this:

Form

      <form action="{{ url('contact') }}" method="POST">
        {{ csrf_field() }}
...
          <input type="email" name="landlordsemail" id="landlordsemail" value="{{ $posts->user_email }}" hidden>
...
      </form>

Route

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

PostsController.php

    public function sendEmail(Request $request)
    {
        $this->validate($request, [
            'email' => 'required|email',
            'subject' => 'min:3',
            'message' => 'min:10'
            ]);
        $data = array(
            'email' => $request->email,
            'subject' => $request->subject,
            'bodyMessage' => $request->message,
            'landlordsemail' => $request->landlordsemail
            );
        Mail::send('emails.contact', $data, function($message) use ($data){
            $message->from($data['email']);
            $message->to( $data['landlordsemail'] );
            $message->subject($data['subject']);
        });

        Session::flash('success', 'Your email was sent.');

        return redirect()->route('home');
    }

Thanks again for all of your help guys! I really appreciate it.

I'm just learning Laravel and have been watching the videos and building my own projects to learn. Sometimes I make some stupid mistakes and I really appreciate your help to resolve these issues. Hopefully one day I'll be as good as you guys! :)

All the best,

Brad

almost_pitt left a reply on Pass A Variable Into A Data Array To Send Email

I've then tried to dd($posts); instead. What's interesting is that it shows that +exists: false.

Post {#213 ▼ #fillable: array:65 [▶] #connection: null #table: null #primaryKey: "id" #keyType: "int" +incrementing: true #with: [] #withCount: [] #perPage: 15 +exists: false +wasRecentlyCreated: false #attributes: [] #original: [] #casts: [] #dates: [] #dateFormat: null #appends: [] #events: [] #observables: [] #relations: [] #touches: [] +timestamps: true #hidden: [] #visible: [] #guarded: array:1 [▶] }

almost_pitt left a reply on Pass A Variable Into A Data Array To Send Email

Sorry about the confusion @Snapey and thanks for the explanation!

To clarify, I want to use the same {{ $posts->user_email }} that I can use in Blade, in the controller to send this person an email with information filled out in a form.

Looking at the first solution, it looks like I didn't pass the variable correctly. I'm not sure why.

Given this:

public function sendEmail(Request $request, Post $posts)
{
$email = $posts->user_email;
dd($email);
...
}

I simply get NULL in the browser.

almost_pitt left a reply on Pass A Variable Into A Data Array To Send Email

Hmmm, I tried to pass in the $posts->id, like so:

return $user = Post::all()->where('id', $posts->id )->pluck('user_email');

but, then got the error

(1/1) ErrorException Undefined variable: rooms

Then, I tried to identify the variable prior to this

$posts = Post::all();

to which, I got the following error:

(1/1) Exception Property [id] does not exist on this collection instance.

However, the ID definitely exists...

So, I tried to pass post in the function sendEmail

  public function sendEmail(Request $request, Post $post)

only to receive the same error.

Any ideas?

almost_pitt left a reply on Pass A Variable Into A Data Array To Send Email

However.... I had another idea

When I use

return $user = Post::all()->where('id', 1 )->pluck('user_email');

I get the email of the poster. The problem is that I am using 1 instead of a dynamic input that would give me the id of the current page. Any idea how to get that ID?

Thanks again for your help guys! I think we're getting close!

almost_pitt left a reply on Pass A Variable Into A Data Array To Send Email

Thanks @Dry7 . Unfortunately, this still gives me this error:

(1/1) ErrorException Trying to get property of non-object

I cleaned up the code a bit. Here is what I have:

    public function sendEmail(Request $request)
    {
        $posts = Post::all();
        $posts = Post::with('user_email')->where('id', $request->input('id'))->first();

        return $landlordsemail = $posts->user_email;

        $this->validate($request, [
            'email' => 'required|email',
            'subject' => 'min:3',
            'message' => 'min:10'
            ]);

        $data = array(
            'email' => $request->email,
            'subject' => $request->subject,
            'bodyMessage' => $request->message,
            'landlordsemail' => $landlordsemail
            );

        Mail::send('emails.contact', $data, function($message) use ($data){
            $message->from($data['email']);
            $message->to( $data['landlordsemail'] );
            $message->subject($data['subject']);
        });

        Session::flash('success', 'Your email was sent.');

        return redirect()->route('home');
    }

Then, I have tried to dd($posts) after

        $posts = Post::with('user_email')->where('id', $request->input('id'))->first();

I only get "null." So, it seems like the id isn't matching the input id....

13 Sep
1 year ago

almost_pitt left a reply on Pass A Variable Into A Data Array To Send Email

Okay, now here's a twist...

If I put

$posts = Post::first();

Then, I get the first email address in the table of posts. So, I am now getting at least an email address, but I'm not getting the right one.

So, with many posts, the problem seems to be selecting the post that I am currently on.... is there somewhere that I can use

$this

or some other command to imply to use the post owner's email?

almost_pitt left a reply on Pass A Variable Into A Data Array To Send Email

Thanks @mindz , but unfortunately I still get the same error.

(1/1) Exception Property [user_email] does not exist on this collection instance.

almost_pitt left a reply on Pass A Variable Into A Data Array To Send Email

Thanks @Dry7

I have declared it in the function and I have

public function sendEmail(Request $request, Post $post)
    {
        $posts = Post::all()->get();
    ...
    }

and I have declared it above

use App\Room;

but, I get another error now.

(1/1) FatalThrowableError Type error: Too few arguments to function Illuminate\Support\Collection::get(), 0 passed in /Users/code/app/Http/Controllers/PostsController.php on line 338 and at least 1 expected

Any idea?

almost_pitt started a new conversation Pass A Variable Into A Data Array To Send Email

Hi guys,

I'm trying to put a contact form into a site where users can post. I would like the email to be sent to the posters.

I can show the poster's email address on the page using blade,

{{$posts->user_email}}

However, when I try to put this into my sendMail function, it cannot read find the email address.

public function sendEmail(Request $request)
{
    $rooms = Room::all();
    $postersemail = $posts->user_email;

    $this->validate($request, [
        'email' => 'required|email',
        'subject' => 'min:3',
        'message' => 'min:10'
        ]);

    $data = array(
        'email' => $request->email,
        'subject' => $request->subject,
        'bodyMessage' => $request->message,
        'postersemail' => $postersemail
        );

    Mail::send('emails.contact', $data, function($message) use ($data){
        $message->from($data['email']);
        $message->to( $data['postersemail'] );
        $message->subject($data['subject']);
    });

    return redirect()->route('home');
}

When I do this, I get the following error:

(1/1) Exception Property [user_email] does not exist on this collection instance.

Any idea why this function cannot find the user_email, but blade can?

Thanks!

09 Sep
1 year ago

almost_pitt left a reply on Find User's Email Through The Post To Be Able To Email Them With Mail

"If this is the case then store the guest's email address as a post attribute"

I'm actually trying to do that within my posts table.

$table->string('user_email')->unique();

For some reason, this came up blank.

almost_pitt left a reply on Find User's Email Through The Post To Be Able To Email Them With Mail

Good point Snapey. Sorry, let me clarify.

Only registered users can post and they must register with their email address.

almost_pitt left a reply on Find User's Email Through The Post To Be Able To Email Them With Mail

I have the feeling I may need to use something like this:

$user->email = DB::table('users')->where('id', $post->user_id )->first();

almost_pitt started a new conversation Find User's Email Through The Post To Be Able To Email Them With Mail

Hey guys,

Imagine I have a blog where guests can post. Then, others can contact the post creator directly through the post's creator's post. In my Mail::send function, how would I find the post creator's email to have this email go directly to them?

I was trying something like this with a lot of variations, but am getting nowhere.

$message->to( $post->user_id->email);

So, essentially I'm trying to use the current post to grab the user's ID, then from there, get their email. Any ideas?

Thanks a lot guys!!

05 Sep
1 year ago

almost_pitt left a reply on (1/2) ErrorException Undefined Property: Illuminate\Pagination\LengthAwarePaginator::$photos

@Cinek - I love you, man.

Amazing! Simple and beautiful. This works :)

I've been trying so many different solutions, but was such an idiot. It was actually within a foreach loop with rooms earlier. I just needed to remove that S from the 3rd line (@foreach($rooms->photos as $photo))

Thanks again @Cinek !!

almost_pitt started a new conversation (1/2) ErrorException Undefined Property: Illuminate\Pagination\LengthAwarePaginator::$photos

Hey guys,

I'm following the Build Project Flyer with Me series and am trying to modify it a bit. I have successfully been able to upload photos and their thumbnails and display them on show.blade.php. However, when I try to input the same code to display the photos on another page, such as index.blade.php, I get the following error:

(1/2) ErrorException Undefined property: Illuminate\Pagination\LengthAwarePaginator::$photos

It seems that the $photos variable was not passed to the other pages.

I have tried different ways to pass the $photos variable to the index route with no luck. Any idea what I could do here?

Here is the code that works perfectly well in the show.blade.php, but breaks index.blade.php

@foreach($rooms->photos as $photo)
  <img src="{{ '/' . $photo->thumbnail_path }}">
@endforeach 

Then, here is what I have in the RoomsController:

public function index()
{
    switch (request('filter')) {
        case 'me':
            $results = Room::where('user_id', Auth::id())->paginate(10);
        break;
        case 'least_expensive':
            $results = Room::orderBy('price', 'asc')->paginate(10);
        break;
        case 'most_expensive':
            $results = Room::orderBy('price', 'desc')->paginate(10);
        break;
        case 'soonest':
            $results = Room::orderBy('datepicker', 'asc')->paginate(10);
        break;
        case 'latest':
            $results = Room::orderBy('datepicker', 'desc')->paginate(10);
        break;
        default:
            $results = Room::orderBy('created_at', 'desc')->paginate(10);
            break;
    }
    return view('rooms.index', ['rooms' => $results]);
}

and Routes web.php file


...
Route::get('rooms/index', [
  'uses' => '[email protected]',
  'as' => 'rooms.index'
  ]);

...

Route::get('rooms/{slug}', [
  'uses' => '[email protected]',
  'as' => 'room'
  ]);

Any idea how I should pass the $photos variable within the RoomsController? Or is there something else I should be looking at?

Thanks!!

30 Aug
1 year ago

almost_pitt left a reply on Trying To Get Property Of Non-object - For Authorized Users Only

@Snapey - > Sorry for the confusion. I was such an idiot!

I figured out the problem.

Here is how I had my web.php before

<?php

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

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

Route::get('{provider}/auth', [
  'uses' => '[email protected]',
  'as' => 'social.auth'
  ]);
Route::get('/{provider}/redirect', [
  'uses' => '[email protected]_callback',
  'as' => 'social.callback'
  ]);
Route::get('rooms/index', [
  'uses' => '[email protected]',
  'as' => 'rooms.index'
  ]);
Route::get('rooms/{slug}', [
  'uses' => '[email protected]',
  'as' => 'room'
  ]);

Route::group(['middleware'=>'auth'], function() {

  Route::get('rooms/create', [
    'uses' => '[email protected]',
    'as' => 'rooms.create'
    ]);
  Route::post('rooms/store', [
    'uses' => '[email protected]',
    'as' => 'rooms.store'
    ]);
  Route::get('rooms/edit/{slug}', [
    'uses' => '[email protected]',
    'as' => 'rooms.edit'
    ]);
  Route::put('rooms/update/{id}', [
    'uses' => '[email protected]',
    'as' => 'rooms.update'
    ]);
  Route::delete('rooms/delete/{slug}', [
    'uses' => '[email protected]',
    'as' => 'rooms.destroy'
    ]);
});

Notice how the rooms/{slug} is above rooms/create. Well, the problem with this is that it thinks that "create" is a slug and it can't find it in the database.

I figured this out by going to the RoomsController and putting in dd($slug); into the show function. When it told me "create" I found out what was the problem.

To fix this, I needed to not only put the show route at the bottom of the web.php file, but also outside of the auth middleware.

<?php

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

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

Route::get('{provider}/auth', [
  'uses' => '[email protected]',
  'as' => 'social.auth'
  ]);
Route::get('/{provider}/redirect', [
  'uses' => '[email protected]_callback',
  'as' => 'social.callback'
  ]);
Route::get('rooms/index', [
  'uses' => '[email protected]',
  'as' => 'rooms.index'
  ]);

Route::group(['middleware'=>'auth'], function() {

  Route::get('rooms/create', [
    'uses' => '[email protected]',
    'as' => 'rooms.create'
    ]);
  Route::post('rooms/store', [
    'uses' => '[email protected]',
    'as' => 'rooms.store'
    ]);
  Route::get('rooms/edit/{slug}', [
    'uses' => '[email protected]',
    'as' => 'rooms.edit'
    ]);
  Route::put('rooms/update/{id}', [
    'uses' => '[email protected]',
    'as' => 'rooms.update'
    ]);
  Route::delete('rooms/delete/{slug}', [
    'uses' => '[email protected]',
    'as' => 'rooms.destroy'
    ]);
});

Route::get('rooms/{slug}', [
  'uses' => '[email protected]',
  'as' => 'room'
  ]);

Now, everything is working! :)

Thanks again everyone who has spent the time to help me! I really appreciate your feedback and ideas.

And, sorry this was such a stupid mistake. It seems obvious now.

Thanks again,

Brad

29 Aug
1 year ago

almost_pitt left a reply on Trying To Get Property Of Non-object - For Authorized Users Only

@Snapey okay, okay, I like where you're going with this.

So, the questions are: what is wrong with the slug and how do the create and show pages interact?

Ideas:

Idea 1

The only connection from the RoomsController.php to the slug, other than creating it, is:

return redirect()->route('room', ['slug' => $room->slug]);

To see if this was the problem, I commented this out and replaced it with

return redirect()->route('/home');

Unfortunately, the problem persisted.

Idea 2

Since authorized users don't have access to the create route when show the show route is open to all users, maybe I should leave access to the $slug variable to all users as well.

I went to the AppServiceProvider.php to try to share this with all users:

        $slug = Room::all('slug');
        View::share('slug', $slug);

I'm not sure if that is the right syntax, but, again, unfortunately, that didn't work.

Idea 3

I also tried to pass the $slug into the store method in the RoomsController

public function store(Request $request, $slug)

This also had no effect.

Idea 4

So, the authorized users don't have access to the create route when show the show route is open to all users. However, the unauthorized users don't have access to the show route whenever it is in the Auth middleware. (Makes sense.)

Can I leave it open another way?

Within the RoomsController, I tried to give unauthorized users access to the show route by changing


    public function show($slug)
    {
        return view('rooms.show')->with('rooms', Room::where('slug', $slug)->first());
    }

to

    public function show($slug)
    {
        if(Auth::guest())
        {
            return view('rooms.show')->with('rooms', Room::where('slug', $slug)->first());
        }
        if(Auth::check())
        {
            return view('rooms.show')->with('rooms', Room::where('slug', $slug)->first());
        }
    }

Unfortunately, this also didn't work.

28 Aug
1 year ago

almost_pitt left a reply on Trying To Get Property Of Non-object - For Authorized Users Only

@Snapey , Good idea, but, no, I don't have any scope on the model so that an authorized user can only see his own rooms. In fact, I'd like everyone to be able to see all rooms.

almost_pitt left a reply on Trying To Get Property Of Non-object - For Authorized Users Only

@thomaskim , Interesting idea!

I get a different error

(1/2) ModelNotFoundException No query results for model [App\Room].

almost_pitt left a reply on Trying To Get Property Of Non-object - For Authorized Users Only

Good idea @kheengz , but, unfortunately, I still get the same problem. :(

almost_pitt left a reply on Trying To Get Property Of Non-object - For Authorized Users Only

@Snapey , how do I set the variable $rooms? I thought I had set it in the roomscontroller. Take a look how I have my show function setup:

RoomsController.php

    public function show($slug)
    {
        return view('rooms.show')->with('rooms', Room::where('slug', $slug)->first());
    }