zarcoder

Experience

8,140

0 Best Reply Awards

  • Member Since 1 Year Ago
  • 75 Lessons Completed
  • 0 Favorites

20th July, 2018

zarcoder left a reply on Vanilla PHP • 2 months ago

I guess I should have picked that up myself. Thank you kindly

zarcoder left a reply on Vanilla PHP • 2 months ago

Thank you. Seems like I get a syntax error?

Parse error: syntax error, unexpected 'foreach' (T_FOREACH) in C:\xampp\htdocs\test\domain.php on line 14

zarcoder started a new conversation Vanilla PHP • 2 months ago

I'm a paying Laracasts subscriber but I'm not sure whether I'm allowed to ask vanilla php questions here? Since Jeff did do a PHP Practitioner I'll ask away...

I have a text file with various names, tags, delimiters and emails in it. I want to extract the domain part of all the emails in this text file which I achieved to do (So [email protected] now output example.com). Now I need to get unique results and sort the domain names alphabetically. If you look at the code below I can't use array_unique() as the output is not an array, but a string. Do I need to explode() the data? If so, how do I echo the strings? I don't want the var_dump or print_r output. An example would help very much.

Here is the code I've written thus far.

<?php

$string = file_get_contents('text.txt');
$pattern = '/[a-z0-9_\-\+][email protected][a-z0-9\-]+\.([a-z]{2,3})(?:\.[a-z]{2})?/i';
$result = preg_match_all($pattern, $string, $matches);
if($result) {
    foreach(array_unique($matches[0]) as $email) {
        $domain = strstr($email, '@', false);
        $domain1 = str_replace('@', '', $domain);
        echo $domain1 . '<br />';
    } 
}

zarcoder left a reply on Reservation Form To Be Emailed • 2 months ago

When I commented out the following code in the postReservation controller function and and did a dd right after that, the mail went through.

$request->validate([
            'name' => 'required|string|min:2',
            'email' => 'required|email',
            'phone' => 'required|digits:10',
            'date' => 'required|date_format:Y/m/d|after:today',
            'seats' => 'required|integer',
            'message' => 'min:10'
        ]);

I added

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

to my form and realised that the date format was incorrect. My validation rules stated Y/m/d and it should have been Y-m-d. I fixed that and now its working.

Thanks for the assistance and apologies again for the hassle.

17th July, 2018

zarcoder left a reply on Reservation Form To Be Emailed • 2 months ago

Thanks for the feedback. I still don't have a solution but will keep digging and post my answer once it's working

16th July, 2018

zarcoder left a reply on Reservation Form To Be Emailed • 2 months ago

Oh, apologies - I didn't know tagging was unacceptable. I'll have to check the log files then.

zarcoder left a reply on Reservation Form To Be Emailed • 2 months ago

Any ideas @bobbybouwmann, @Snapey, @Cronix on how to get my reservation form to email the details? Like, I said, when I dd the form data, I can view the array output.

PS - I know that the $message->from and $message->to in the controller should ideally have the same email address. I'm just using a different ->to address for testing purposes.

14th July, 2018

zarcoder left a reply on Reservation Form To Be Emailed • 2 months ago

Yes, when I dd the data, I can see it

array:9 [▼
  "_token" => "obsuu81ZQ3RuuawYfiM9T3vNggtKkWYzypaOYq7Y"
  "name" => "JP"
  "email" => "[email protected]"
  "phone" => "0741112225"
  "datepicker" => "2018-08-19"
  "time" => "10:00"
  "seats" => "12"
  "message" => "Test Message"
  "url" => null
]

zarcoder started a new conversation Reservation Form To Be Emailed • 2 months ago

I created a contact form that emails the details to the client. The email is sent successfully and all validation with error messages work. I'm also creating a reservation form which should essentially do the same as the contact form. I've setup my reservation routes, views and controller but the email is not sent to mailtrap.io. I'm using the same controller for both the contact and reservation form. Not sure if that is maybe an issue?

My web.php file

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

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

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

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

My PageController

class PageController extends Controller
{
    
    public function reservation()
    {
        return view('reservation');
    }

    public function postReservation(Request $request)
    {
        //dd($request->all()); -> Fill in data to test if form works
        $request->validate([
            'name' => 'required|string|min:2',
            'email' => 'required|email',
            'phone' => 'required|digits:10',
            'date' => 'required|date_format:Y/m/d|after:today',
            'seats' => 'required|integer',
            'message' => 'min:10'
        ]);

        $data = array (
            'name' => $request->name,
            'email' => $request->email,
            'phone' => $request->phone,
            'date' => $request->date,
            'time' => $request->time,
            'seats' => $request->seats,
            'reservationMessage' => $request->message,
        );

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

        return redirect('reservation')->with('success', 'Thank you. We will contact you to confirm the booking');
    }

    public function contact()
    {
        return view ('contact');
    }

    public function postContact(Request $request)
    {
        //dd($request->all()); -> Fill in data to test if form works
        $request->validate([
            'name' => 'required|string|min:2',
            'email' => 'required|email',
            'number' => 'required|digits:10',
            'subject' => 'required|min:3',
            'message' => 'required|min:10'
        ]);

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

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

        return redirect('contact')->with('success', 'Your message has been sent. We will reply promptly');
    }
}

My Reservation Form

<form method="post" id="reservation-form" action={{ action('[email protected]') }}>
                            {{ @csrf_field() }}
                            <div class="row">
                                <div class="col-md-4">
                                    <label>Name*</label>
                                    <p><input type="text" name="name" class="reservation-fields" required/></p>
                                </div>
                                <div class="col-md-4">
                                    <label>Email*</label>
                                    <p><input type="text" name="email" class="reservation-fields" required/></p>
                                </div>
                                <div class="col-md-4">
                                    <label>Phone*</label>
                                    <p><input type="text" name="phone" class="reservation-fields" required/></p>
                                </div>
                            </div>
                            <!--end row-->
                            <div class="row">
                                <div class="col-md-4">
                                    <label>Date*</label>
                                    <p><input type="date" name="datepicker" id="datepicker" class="reservation-fields" size="30" required/></p>
                                </div>
                                <div class="col-md-4">
                                    <label>Time*</label>
                                    <p>
                                        <select name="time" class="reservation-fields" >
                                            <option value="10:00">10:00</option>
                                            <option value="11:00">11:00</option>
                                            <option value="12:00">12:00</option>
                                            <option value="13:00">13:00</option>
                                            <option value="14:00">14:00</option>
                                            <option value="15:00">15:00</option>
                                            <option value="16:00">16:00</option>
                                        </select>
                                    </p>
                                </div>
                                <div class="col-md-4">
                                    <label>Seats*</label>
                                    <p><input type="text" name="seats" class="reservation-fields" required/></p>
                                </div>
                            </div>
                            <!--end row-->
                            <label>Special Requests</label>
                            <p> <textarea name="message" id="message2" class="reservation-fields" cols="100" rows="4" tabindex="4"></textarea></p>
                            <p class="antispam">Leave this empty: <input type="text" name="url" /></p>
                            <p class="alignc"><input type="submit" value="Book Now" id="submit" /></p>
                        </form>

My Reservation Email Template


<p>Name: {{$name}}</p>

<p>Email: {{$email}}</p>

<p>Tel Nr: {{$phone}}</p>

<p>Date: {{$date}}</p>

<p>Time: {{$time}}</p>

<p>Seats: {{$seats}}</p>

<p>Message: {{$reservationMessage}}</p>

13th July, 2018

zarcoder left a reply on Laravel Contact Form • 2 months ago

Fantastic, very helpful! Thank you @Cronix

zarcoder left a reply on Laravel Contact Form • 2 months ago

please see my warning about the from address.

Thanks for the warning. So this is something new... again :). Here's my context. I'm creating a simple website for my 1st client (restaurant owner) who has a contact form on his site. He just wants to receive emails from people who want to contact him from his website.

He will then take that email and copy it into his personal email host and answer any questions.

So, as I understand it, the 'from' attribute will identify the from email address of the person enquiring. But now that I think about that, this detail is captured in one of my form fields (email).

Hhmm, ok so I should hardcode the 'from' attribute to my personal email address in order to avoid ending up in a spambox.

Isn't it better just to avoid the 'from' attribute altogether?

May be basics to you, but I'm still climbing the mountain of learning php / laravel :)

12th July, 2018

zarcoder left a reply on Laravel Contact Form • 2 months ago

Sorry man, we were typing the same time it seems :). Only saw your message now

zarcoder left a reply on Laravel Contact Form • 2 months ago

Not to worry, I figured it out. Should not use

Session::flash('success', 'Your email has been sent');

Should use

$request->session()->flash('status', 'Good One');

instead

zarcoder left a reply on Laravel Contact Form • 2 months ago

@Cronin, so I got the message to work. It's being sent to mailtrap so I know it works. After the mail has been sent, I'm also being redirected to the contact page as per my redirect.

However, my success message does not display? I can't seem to get the success message right. Any thoughts?

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Session;

class PageController extends Controller
{

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

    public function postContact(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|min:2|string',
            'email' => 'required|email',
            'mobile' => 'required|digits:10',
            'message' => 'required|min:10'
        ]);

        $data = array(
          'name' => $request->name,
          'email' => $request->email,
          'mobile' => $request->mobile,
          'bodyMessage' => $request->message
        );

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

        Session::flash('success', 'Your email has been sent');

        return redirect('contact');
    }

}

zarcoder left a reply on Laravel Contact Form • 2 months ago

@Cronix, I am a beginner but have done a few projects in laravel focussing on the basics. But I do know how to create, forms, controllers, views, routes and validation. I will follow your guidance and give feedback. Thanks for the reply

@newbie360 - Don't know what you're on about? I know it's front-end but has back-end functionality, hence the question.

10th July, 2018

zarcoder started a new conversation Laravel Contact Form • 2 months ago

I purchased a html template from themeforest and I'm in the process of converting all the files into blade files. Bit of a mission I must say.

I now need to setup my contact form. I'm quite lost at the moment. I did read through the Laravel mail docs but I'm struggling. So the theme included the contact form (in html obviously) as well as the php 'contact-process file. Both files are shown below.

My question is, how do I convert this to laravel? I'm not sure which steps to follow. How can I make this contact form work in laravel?

The Form:

<form method="post" id="contact-form" action='contact-process.php'>
                         <label>Name</label>
                         <p><input type="text" name="name" class="reservation-fields" /></p>
                         <label>Email</label>
                         <p><input type="text" name="email" class="reservation-fields"/></p>
                         <label>Subject</label>
                         <p><input type="text" name="subject" class="reservation-fields" /></p>
                         <label>Message</label>
                         <p> <textarea name="message" id="msg-contact" class="reservation-fields" rows="7"></textarea></p>
                         <p class="antispam">Leave this empty: <input type="text" name="url" /></p>
                         <p class="contact-btn"><input type="submit" value="Send message" id="submit"/></p>
                      </form>

PHP File:

<?php

$recipient = "[email protected]";
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];

if (isset($_POST['email'])) {   
    if (preg_match('(\w[-._\w]*\[email protected]\w[-._\w]*\w\.\w{2,})', $_POST['email'])) {
        $msg = 'E-mail address is valid';
    } else {
        $msg = 'Invalid email address';
    }

  $ip = getenv('REMOTE_ADDR');
  $host = gethostbyaddr($ip);   
  $mess = "Name: ".$name."\n";
  $mess .= "Email: ".$email."\n";
  $mess .= "Subject: ".$subject."\n";
  $mess .= "Message: ".$message."\n\n";
  $mess .= "IP:".$ip." HOST: ".$host."\n";
  
  $headers = "From: <".$email.">\r\n"; 
  
   if(isset($_POST['url']) && $_POST['url'] == ''){

       $sent = mail($recipient, $subject, $mess, $headers); 
} 

  

} else {
    die('Invalid entry!');
}

26th June, 2018

zarcoder left a reply on Some Beginner PHP Advice • 3 months ago

Thanks for the advice guys. I take it too heart. @Jerome2116 I'm definitely a reader. I see however the rating on the recommended PHP-MySQL book is not that great. Seems like there's books with better (and more) ratings. I should also keep in mind to get a book that is not dated. Thanks for the tips.

@martinbean - I agree. I think I'm going to build a few sites in vanilla php and revisit the laravel frame work by year-end.

Thanks also @ejdelmonico for your good advice.

25th June, 2018

zarcoder started a new conversation Some Beginner PHP Advice • 3 months ago

Hi, I am a beginner PHP coder.

So I have already built an CRUD with 1 to many and many to many relationships going through various tutorials. I am also following Jeffrey's courses and its now my 2nd time going through the laravel from scratch 5.4 series.

My concern is I don't understand everything. Is my approach correct? I'm learning laravel 1st but at the same time there is a lot of PHP concepts I have not mastered as yet. Or is it normal to feel you know very little.

Lastly, and I'm not sure if this is the forum but let me ask anyway. As an aspirant web developer, what is the best way to make money working for yourself given my beginner experience?

13th June, 2018

zarcoder left a reply on JQuery Validation Plugin & Laravel • 3 months ago

So at the end of the day, the fix was a really stupid one. I spoke to one of my developer friends and he advised that I should place the reference in the and not at the bottom of the master file . That fixed it! Why though? I have no idea...

<!DOCTYPE html>
<html>
    <head>
        <title>ProPay_CRUD - @yield('title')</title>
        <link rel="stylesheet" href="{{asset('css/bootstrap.css')}}">
        <link rel="stylesheet" href="{{asset('css/custom.css')}}">
        <script src="{{asset('js/jquery-3.3.1.js')}}"></script>
    </head>
    <body>

        @include('shared.header')

        <div class="container">
            <div class='row'>
                <div class='col justify-content-center'>
                    <p></p>
                    @include('shared.errors')
                    @include('shared.message')

                    @yield('content')
                </div>
            </div>
        </div>

        @include('shared.footer')

        <script src="{{asset('js/bootstrap.js')}}"></script>
        <script src="{{asset('js/delete_confirm.js')}}"></script>
        <script src="{{asset('js/jquery.validate.min.js')}}"></script>
        <script src="{{asset('js/additional-methods.min.js')}}"></script>
        <script src="{{asset('js/validation.js')}}"></script>
    </body>
</html>

9th June, 2018

zarcoder started a new conversation JQuery Validation Plugin & Laravel • 3 months ago

My front-end validation rules don't seem to work. Herewith my create.blade.php and member_form.blade.php files

create.blade.php

{!! Form::model($member, ['action' => '[email protected]', 'id' => 'createform']) !!}

    @include('members.partials.member_form')

    <button class="btn btn-success" type="submit">Save Member</button>

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

<script>
    $(document).ready(function(){
        $("#createform").validate({
            rules: {
                name: {
                    required:true
                }
            }
        });
    });
</script>

member_form.blade.php

<div class="form-group">
{!! Form::label('name', 'First Name:') !!}
{!! Form::text('name', null, ['class' => 'form-control']) !!}
</div>

When I'm testing the Jquery validation plugin, I only get my back-end validation messages. No front-end validation message appear when I try to create a blank create form where no name input is entered. Did I enter the js script in the wrong place or is my code wrong? Documentation seem to be inline with what I coded here.

zarcoder started a new conversation Foreign Key Migration Failing • 3 months ago

I need to change the onDelete('cascade') method from 'cascade' to 'restrict' on 2 foreign key columns. I've created the migration file and this is what I've got in my up and down functions.

public function up()
    {
        Schema::table('interests_members', function (Blueprint $table) {
            $table->foreign('interest_id')->references('id')->on('interests')->onDelete('restrict');
            $table->foreign('member_id')->references('id')->on('members')->onDelete('restrict');
        });
    }

    public function down()
    {
        Schema::table('interests_members', function (Blueprint $table) {
            $table->dropColumn('interest_id');
            $table->dropColumn('member_id');
        });
    }

When I try to run php artisan migrate, I get the following command line error

Illuminate\Database\QueryException  : SQLSTATE[23000]: Integrity constraint violation: 1022 Can't write; duplicate key in table '#sql-6b48_76' (SQL: alter table `interests_members` add constraint `interests_members_interest_id_foreign` foreign key (`interest_id`) references `interests` (`id`) on delete restrict)

  at G:\laragon\www\tomcrud\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668|

  Exception trace:

  1   PDOException::("SQLSTATE[23000]: Integrity constraint violation: 1022 Can't write; duplicate key in table '#sql-6b48_76'")
      G:\laragon\www\tomcrud\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458

  2   PDOStatement::execute()
      G:\laragon\www\tomcrud\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458

How do I fix this?

7th June, 2018

zarcoder left a reply on Display Many To Many In Show Blade • 3 months ago

Thx a mil

zarcoder started a new conversation Display Many To Many In Show Blade • 3 months ago

I have a members, interests and interests_members table where 1 member can have multiple interests and 1 interest can be shared by multiple members. When testing the interests_members table update 100%.

The interests_members table have the following columns:

  1. id
  2. interest_id -> foreign key
  3. member_id -> foreign key

My problem is, I don't know what syntax to use in order to display the interests per member in the show blade? In need help with the Interest field in the code block below.

show.blade.php:

    <h1>Member Details: </h1>
    <p>Name: {{$member->name}}</p>
    <p>Surname: {{$member->surname}}</p>
    <p>ID Nr: {{$member->id_number}}</p>
    <p>Language: {{$member->language->name}}</p> 
    <p>Interest: {{??????}}</p>

zarcoder left a reply on Many To Many | View Error • 3 months ago

Thanks @tykus. Ok so I will do that. But I see no documentation about setting up foreign keys then? Where can I find that info?

6th June, 2018

zarcoder left a reply on Many To Many | View Error • 3 months ago

I ran: php artisan make:model Interest --migration to create the Interest Model and interests table in the db. According to the docs it is my understanding that Laravel will automatically create a interest_member table with the foreign keys setup automatically. Am I misreading that in the Eloquent >> Relationships >> Many to Many part of the Laravel 5.6 docs?

The docs does not give any examples of setting up this 3rd table nor how to configure the foreign key, hence my assumption that all of this is setup automatically.

zarcoder started a new conversation Many To Many | View Error • 3 months ago

I'm fairly beginner so please bear with me... I have a many to many relationship. My main object is a members table and these members can have multiple interests as a dropdown selection. A interest can also have multiple members.

When I test my create view I get the following error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'tomcrud.interest_member' doesn't exist (SQL: select `interests`.*, `interest_member`.`member_id` as `pivot_member_id`, `interest_member`.`interest_id` as `pivot_interest_id` from `interests` inner join `interest_member` on `interests`.`id` = `interest_member`.`interest_id` where `interest_member`.`member_id` is null) (View: G:\laragon\www\tomcrud\resources\views\members\partials\member_form.blade.php) (View: G:\laragon\www\tomcrud\resources\views\members\partials\member_form.blade.php)

If I read laravel docs correctly, the interest_member table should be created automatically with all the relevant keys. I can't see such a table in my schema. I can however see my members and interests tables.

I believe my Models are configured correctly:

Member Model:

class Member extends Model
{
    public function interests()
    {
        return $this->belongsToMany('App\Interest', 'interest_member');
    }
}

Interest Model:

class Interest extends Model
{
    public function members()
    {
        return $this->belongsToMany('App\Member');
    }
}

My MemberController create() function:

public function create()
    {
        $member = new Member;
        $data = array();
        $data['member'] = $member;
        $data['languages'] = Language::pluck('name', 'id');
        $data['interests'] = Interest::pluck('name', 'id');

        return view('members.create', $data);
    }

The multi select dropdown portion of my member_form blade:

 <div class="form-group">
    {!! Form::label('interest_id[]', 'Interest:') !!}
    {!! Form::select('interest_id[]', $interests, $member->interests->pluck('id'), ['multiple' => true, 'class' => 'form-control']) !!}
</div>

Please advise where I err. Thanks

5th June, 2018

zarcoder left a reply on One To Many Relationship Logic • 3 months ago

Thanks @Snapey. You're feedback makes a lot of sense. Its logical.

zarcoder started a new conversation One To Many Relationship Logic • 3 months ago

I'm learning php and laravel. I'm doing a crud test for a company and if I pass I can be considered for joining the dev team. One of the requirements of the crud test is that a member (who is the main object) may have one language from a list of multiple language options. Obviously one language can be linked to multiple members.

So if I read laravel docs correctly, the foreign key between the main model (Member) and the secondary model (Language) will be setup automatically. My question is how to setup the relationship logically.

one of the columns in my members table is a language_id column and the languages table consist of id (obviously) and the name of the language.

According to examples the relationship should look something like this:

Member Model:

class Member extends Model { public function language() { return $this->hasMany('App\Language'); } }

Language Model:

class Language extends Model { public function member() { return $this->belongsTo('App\Member'); } }

But does this make sense? The Member model is essentially saying the member can have multiple languages. But that is not the case. The member can only have 1 language.

Can you please help me clarify this issue.

Thanks

Edit Your Profile
Update

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