Buy your loved one the ultimate gift. Lifetime gift certificates are $100 off.

Laravelephant

Experience

10,950

3 Best Reply Awards

  • Member Since 2 Years Ago
  • 117 Lessons Completed
  • 2 Favorites

12th December, 2017

Laravelephant left a reply on Send Multiple SMS From One Notification • 1 day ago

Hey @martinbean

Thanks for this, I've managed to sort the problem (I just trigger a separate notification from the controller and do the loop there).

I agree with your point re a large amount of SMS but this is something that a client specifically requested so it's up to them.

Laravelephant started a new conversation Send Multiple SMS From One Notification • 1 day ago

Hey

So I have a notification which I want to send a series of SMS to a single user. I have something like this:

   {
      return (new NexmoMessage)
      ->content('Here is the intro message.');
      foreach($this->orders as $order) {
       return (new NexmoMessage)
       ->content('Here are multiple order notifications.');
   }
}````

The first one goes through ok but the rest don't. Any idea on how to trigger multiple SMS to go out?

7th December, 2017

Laravelephant left a reply on Generate A Number • 6 days ago

Hey @36864

That worked perfectly! It seems really obvious with hindsight. Thanks!

Laravelephant left a reply on Generate A Number • 6 days ago

@martinbean - whoops! I meant I need to add a number onto the end and increment that last digit. Fair point though.

@kobear - Thanks this is pretty useful to know but I think that I'm still stuck with the same issue in that I need to know the latest po_number to increment from.

Laravelephant left a reply on Generate A Number • 6 days ago

Hey @36864

Thanks for this. It's along the lines of what I was wanting to do but the issue is that I don't know what the increment needs to be. There are two columns: job and po_number.

The po_number is always going to increment, but when creating a new entry, I only have the job number.

So I need to find the latest po_number based on the job_number and then increment by one.

Laravelephant left a reply on Generate A Number • 6 days ago

Sorry, I'm probably being a bit unclear. So basically I've got a DB with a bunch of existing values. Each row has a job field and a newJob field.

When a new row is entered, I want to ensure that newJob is always one higher than any previous instance. So if we had the base number of 1234 then there might be several rows with job as 1234 and their newJob field would be 12341, 12342, 12343 and so on.

I've written a small function like this for instance:

 public function generatePONumber($jobNumber)
    {
        $base = Order::where('job_number', $jobNumber)->orderBy('po_number')->get();
        if(count($base)) {
            if($base->job_number) {
                $jobNumber = $base->jobNumber + 1;
            } 
            else {
                $jobNumber = $base + 1;
            }
            return $jobNumber;
        }
    }

Laravelephant started a new conversation Generate A Number • 6 days ago

What would you say is the best way to do this?

I am taking a number from a variable $job and I want to create a new variable ($newJob) which is $job plus an increment. This may have happened in the past so I need to be able to ensure that I'm always going one number higher.

For example:

$job = 1234. In the first pass I would want to be $newJob = 12341.

In the second then $newJob = 12342 and so on.

Each of these variables is getting stored in the DB.

Any suggestions?

5th December, 2017

Laravelephant left a reply on WhereYear Not Getting Results • 1 week ago

I managed to fix it by doing a check on the parameter like so:

if($request->dateFrom !== null) {
            $order->whereBetween('created_at', 
                [
                    Carbon::parse($request->dateFrom), 
                    Carbon::parse($request->dateTo)
                ]);
        } elseif($request->has('year') !== null) {
            $order->whereYear('created_at', $request->year);
        } 

Thanks for the help though :)

Laravelephant left a reply on WhereYear Not Getting Results • 1 week ago

Ok, I just ran the whereYear on its own and it works fine. So it is being interefered with by the if statement for the dateFrom somehow.

Laravelephant left a reply on WhereYear Not Getting Results • 1 week ago

That's what I thought too, but it's returning a null result where it should be coming back with ~50 rows.

Laravelephant left a reply on WhereYear Not Getting Results • 1 week ago

Here is the whole snippet:

    $order = (new Order)->newQuery();

        if ($request->has('report')) {
            $order->where('status', $request->report);
        }

        if($request->has('supervisors')) {
            $order->where(function($query) use ($request) {
                foreach ($request->supervisors as $key => $supervisor) {
                    if ($key == 0)  {
                        $query->where('supervisor_id', $supervisor);
                    } else {
                        $query->orWhere('supervisor_id', $supervisor);
                    }
                }
            });
        }

        if($request->has('employees')) {
            $order->where(function($query) use ($request) {
                foreach ($request->employees as $key => $employee) {
                    if ($key == 0)  {
                        $query->where('creator_id', $employee);
                    } else {
                        $query->orWhere('creator_id', $employee);
                    }
                }
            });
        }

        if($request->has('dateFrom')) {
            $order->whereBetween('created_at', 
                [
                    Carbon::parse($request->dateFrom), 
                    Carbon::parse($request->dateTo)
                ]);
        }
        elseif($request->has('year')) {
            $order->whereYear('created_at', '2017');
        } 

return $order->get();

}

Laravelephant started a new conversation WhereYear • 1 week ago

Hey

So I'm continuing down my path of doing some Eloquent filters and have noticed that the following isn't working:

if($request->has('dateFrom')) {
            $order->whereBetween('created_at', 
                [
                    Carbon::parse($request->dateFrom), 
                    Carbon::parse($request->dateTo)
                ]);
        }
        elseif($request->has('year')) {
            $order->whereYear('created_at', '2014');
        } 

The whereBetween` query works just fine and reliably selects all the dates between mydateFromanddateTo``` but I can't seem to get all results by a specified year. I've tried wrapping the year in a Carbon instance etc.

Any tips?

4th December, 2017

Laravelephant left a reply on Eloquent Filtering • 1 week ago

This worked! Thanks @VijayKadiyam and @Nash! I think the issue was the where / orWhere.

Laravelephant left a reply on Eloquent Filtering • 1 week ago

array:2 [▼
  0 => "6"
  1 => "16"
]

Laravelephant left a reply on Eloquent Filtering • 1 week ago

Just tested and I am!

Laravelephant left a reply on Eloquent Filtering • 1 week ago

Just gave both snippets a go and am still getting a blank page with no errors. It's just returning null :/

Laravelephant started a new conversation Eloquent Filtering • 1 week ago

Hey

So I've watched the Laracasts video on this but am struggling with an aspect of Eloquent filtering. I've got a single table which I want to grab specific records from.

I don't understand how to iterate over an array that I'm passing in my form request to then get the values from the DB. Code for example:

$order = (new Order)->newQuery();

        if ($request->has('report')) {
            $order->where('status', $request->report);
        }

        if($request->has('supervisors')) {
            foreach($request->supervisors as $supervisor) {
                $order->where('supervisor_id', $supervisor);
            }
        }

return $order->get();

So the supervisors is the array of IDs that I want to match up with the supervisor_id column in my table. This doesn't seem to work though. It just returns a blank page (no errors). If I remove the foreach then I get the expected results.

I've also checked the database to ensure that records exist that can be grabbed with what I'm submitting through the form.

Any ideas?

22nd November, 2017

Laravelephant left a reply on Access Constraint Violation • 3 weeks ago

Hey,

That's what was causing the issue, I have it fixed. Thank you :)

21st November, 2017

Laravelephant left a reply on Access Constraint Violation • 3 weeks ago

Hey

Thanks, correcting the Model helped a bit but has thrown this new error:

"Call to a member function addEagerConstraints() on null"

It doesn't identify the line the error is ocurring on but it seems that my controller isn't loading the relationships of the inspection. Any clues?

Laravelephant started a new conversation Access Constraint Violation • 3 weeks ago

Hey,

I keep getting this error and can't work out why. I have the following relationships:

Inspection Model

public function sections()
    {
        return $this->belongsToMany(InspectionSection::class, 'inspection_sections', 'inspection_id', 'id');
    }

The DB looks like:

  Schema::create('inspection_sections', function (Blueprint $table) {
            $table->integer('inspection_id')->unsigned();
            $table->integer('section_id')->unsigned();
            $table->timestamps();

            $table->foreign('inspection_id')->references('id')->on('inspections')->onDelete('cascade');
            $table->foreign('section_id')->references('id')->on('inspection_section')->onDelete('cascade');
        });
     Schema::create('inspection_section', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('inspection_id')->unsigned();
            $table->timestamps();
            
            $table->foreign('inspection_id')->references('id')->on('inspections')->onDelete('cascade');
        });
    }

And then I'm doing a clone in my controller like so:


        try {
           if(! $request->template) {
            $inspection = new Inspection;
            $inspection->name = $request->name;
            $inspection->save();

        } else {
          $inspection = new Inspection;
          $template = Inspection::findOrFail($request->template);
          $template->load('sections');
          $inspection = $template->replicate();
          $inspection->name = $request->name;
          $inspection->push();

          foreach($template->sections as $section) {
            $clonedSection = $section->replicate();
            $clonedSection->section_id = $section->id;
            $clonedSection->push();
            $inspection->sections()->save($clonedSection);
            foreach($section->questions as $question) {
                $clonedQuestion = $question->replicate();
                $clonedQuestion->inspection_id = $inspection->id;
                $clonedQuestion->section_id = $clonedSection->id;
                $clonedQuestion->push();
                $clonedSection->questions()->save($clonedQuestion);
            }
        }
    }

    sections
    if(count($request->sections)) {
       foreach($request->sections as $section) {
            if(! $inspection->sections->contains($section)) {
                $inspection->sections()->attach($section);  
             }
         }
     }

    if(count($request->users)) {
        foreach($request->users as $user) {
            $inspection->user = new InspectionUser;
            $inspection->user->user_id = $user;
            $inspection->user->inspection_id = $inspection->id;
            $inspection->user->save();
        }
    }

I keep getting this error and don't understand why:

SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'inspection_sections' 

Any help?

15th November, 2017

Laravelephant left a reply on Pivot Table Referring To Same Model • 4 weeks ago

Update:

I had my keys the wrong way around. It should be this:

  public function supervisors()
    {
        return $this->belongsToMany(User::class, 'employee_supervisor', 'supervisor_id', 'employee_id')->withTimestamps();
    }

    public function employees()
    {
        return $this->belongsToMany(User::class, 'employee_supervisor', 'employee_id', 'supervisor_id')->withTimestamps();
    }

Laravelephant started a new conversation Pivot Table Referring To Same Model • 4 weeks ago

Hey

So I've made a basic pivot table to allow a User model to access different roles. I then have added the following in my Model:

    public function supervisors()
    {
        return $this->belongsToMany(User::class, 'employee_supervisor', 'employee_id', 'supervisor_id')->withTimestamps();
    }

    public function employees()
    {
        return $this->belongsToMany(User::class, 'employee_supervisor', 'supervisor_id', 'employee_id')->withTimestamps();
    }

I have a pivot table with the following migration:

Schema::create('employee_supervisor', function (Blueprint $table) {
            $table->integer('employee_id')->unsigned();
            $table->integer('supervisor_id')->unsigned();
            $table->timestamps();

            $table->foreign('employee_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('supervisor_id')->references('id')->on('users')->onDelete('cascade');
        });

This has worked ok but I can't seem to retrieve an employee with their supervisor, or a supervisor with their employees. What am I doing wrong?

13th November, 2017

Laravelephant left a reply on Architecture Question (user Belongs To Another User) • 1 month ago

Hey @martinbean

It's actually a little complex as an employee may be supervised by many users. Maybe a pivot table would be better, but can you do that for the same model? :/

Laravelephant started a new conversation Architecture Question (user Belongs To Another User) • 1 month ago

Hey

So I'm making a little app just now where I have a bunch of users in my users table. I want there to be three roles and I'll use the Spatie roles/permissions package to do that.

The three roles are:

admin supervisor employee

I want a supervisor to have many employees, and the employee to belong to many supervisors.

Ordinarily that would be pretty obviously a many-to-many relationship but it's all taking place on the single User model. What is the correct way to implement this?

31st October, 2017

Laravelephant left a reply on Post Checkbox Values With JS • 1 month ago

Here:

<span class="glyphicon glyphicon-flag high-priority"></span><input type="checkbox" class="checkbox_click" id="{{$issue->id}}" name="{{$issue->id}}" @if($issue->priority === 'high') checked='true' @else '' @endif  value="high">
                    
                    <span class="glyphicon glyphicon-flag medium-priority"></span><input type="checkbox" class="checkbox_click" id="{{$issue->id}}" name="{{$issue->id}}" @if($issue->priority === 'medium') checked='true' @else '' @endif  value="medium">

                    <span class="glyphicon glyphicon-flag low-priority"></span><input type="checkbox" class="checkbox_click" id="{{$issue->id}}" name="{{$issue->id}}" @if($issue->priority === 'low') checked='true' @else '' @endif  value="low">

Laravelephant started a new conversation Post Checkbox Values With JS • 1 month ago

Hey

I'm pretty stuck here and could do with some help. I have three checkboxes which I want to be able to click and un-click to set a value on the DB. I have succeeded in getting it to update based on a click, but can't unset the checkbox and persist it.

Also, I only want to be able to set one checkbox at a time.

Any ideas?

Here is my JS:

$(document).ready(function() {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        
        $('.checkbox_click').click(function(){       
            var currentValue = $(this).attr("value");
            var issue = $(this).attr("id");
            $.ajax({
                url: "/admin/issues/" + issue + "/priority",
                method: 'post',             
                data: {priority: currentValue, _token: $('input[name="csrf-token"]').val()},
                // success: function(data){
                //  alert(data);
                // },
                error: function(){},
            });
        });         
    });

and my controller

public function store (Request $request) {
        return $request;
        $issue = Issue::findOrFail($request->issue);
        if (!empty($request->priority)) {
            $issue->priority = $request->priority;
        } else {
            $issue->priority = NULL;
        }
        $issue->save();
        return back();
    }

12th October, 2017

Laravelephant left a reply on Submit Form With Multiple Values • 2 months ago

Thanks @tykus and @ftrillo that worked perfectly!

Just for reference, is there a better way of structuring this sort of form to avoid needing to use the array etc?

Laravelephant left a reply on Submit Form With Multiple Values • 2 months ago

Hey @ftrillo - I have just implemented that but still having some issues pulling it on the controller end.

Laravelephant left a reply on Submit Form With Multiple Values • 2 months ago

Whoops!

Ok, so I have it pulling the array but maybe it's my controller logic that is funny?

foreach($request as $response) {
            $answer = new Answer;
            $answer->answer = $response->answer;
            $answer->checklist_id = $response->list_id;
            $answer->section_id = $response->section_id;
            $answer->question_id = $response->question_id;
            $answer->save();
        }

When I dd($request) I get this:

 "answer" => array:4 [▼
        0 => "yes"
        1 => "wada"
        2 => "yes"
        3 => "yes"
      ]
      "list_id" => array:4 [▼
        0 => "1"
        1 => "1"
        2 => "1"
        3 => "1"
      ]
      "section_id" => array:4 [▼
        0 => "1"
        1 => "1"
        2 => "5"
        3 => "5"
      ]
      "question_id" => array:4 [▼
        0 => "1"
        1 => "2"
        2 => "6"
        3 => "7"
      ]
    ]

Laravelephant started a new conversation Submit Form With Multiple Values • 2 months ago

This is a stupidly simple question but I'm stuck on it for some reason.

I have a form which is generated dynamically. It contains various fields which could be a textarea, a select, a radio button etc.

Each field has three hidden fields containing: list_id question_id and section_id.

These are pulled directly from the model and are showing up fine when I preview the question's source code.

An example field looks like this:


@if($question->question_type === 'Yes/No')
<select name="answer[]">
    <option value="yes">Yes</option>
    <option value="no">No</option>
</select>
<input type="hidden" name="list_id" value="{{$list->id}}">
<input type="hidden" name="section_id" value="{{$section->id}}">
<input type="hidden" name="question_id" value="{{$question->id}}">
@endif 

In my controller I'm using a foreach loop which grabs the 'answer' field correctly and inserts them as expected. But it renders the $list, $section and $question ids as the same across all the fields.

I know that the foreach isn't catching them, but where am I going wrong in my code?

Thanks

11th October, 2017

Laravelephant left a reply on Save Data Cleanly • 2 months ago

Can't believe I missed that. Working fine, thanks! :)

Laravelephant started a new conversation Save Data Cleanly • 2 months ago

Hey

Suppose I am wanting to take data from a form and save it in a clean way to two separate models. What is the best way to do so?

For example, I have the following models: Quiz and Respondent, and the controller is QuizController.

I'm passing the data to QuizController and can easily save the data to the Quiz model, but I'm taking in several respondents from the form as an array. These will then be saved to a Respondent model.

My (pseudo)code looks like this:

  $quiz = new Quiz;
  $quiz->name = $request->name;
  $quiz->save;
  Respondents::insert($request->respondents);

Surely there is a better way of doing this?

25th September, 2017

Laravelephant left a reply on Relationship Structuring • 2 months ago

Yeah, I had realised that there was nothing in my migration to associate a Reviewer with the Faculty, Class or Grade.

I've now implemented a morphToMany relationship on the Grade model so that the others can access it in a clean way.

I think that's the best way of doing it...

Laravelephant started a new conversation Relationship Structuring • 2 months ago

I'm needing some help on how to structure some relationships.

I have the following models:

Reviewer

Faculty

Class

Student

Grade

The system should work so that a Reviewer is responsible for several Faculty, Class, and Student. All of the models other than Reviewer can have a grade.

I want to be able to access things so that I can go to /class/1 and see all grades for that class, or visit the Reviewer profile page and see all grades they have given.

So far I've made it like so:

Reviewer belongsToMany Grade

Grade belongsToMany Reviewer (with a pivot table)

Grade belongsTo Faculty

Grade belongsTo Class

Grade belongsTo Student

Then Faculty, Class, and Student all have a hasMany on Grade.

The problem is then setting up the DB structure in a sensible way. Does anyone have any recommendations?

22nd September, 2017

Laravelephant left a reply on Retrieving A Related Model's Details • 2 months ago

@tykus - good catch, thanks! It actually didn't affect the execution of the code, but I've switched to a many-to-many either way.

My impression is that the foreach has to happen at some point either way. It's not too messy in the view I guess, I just wanted to see if there was a more elegant way of doing it.

Laravelephant started a new conversation Retrieving A Related Model's Details • 2 months ago

Hey

So my code works but I want to know if there is a neater way of doing this. Essentially I have two models:

Issue
Inspector

The relationship is that:

Inspector belongsToMany Issues Issues hasMany Inspector

I have created a simple view to take a look at my issue which works perfectly, but when I want to view the details of the Inspector(s), I need to do a foreach loop in the view in order to see even one inspector.

I know that this is because the association assumes there will be many, but is there a neater way of doing this rather than doing a loop in the view?

31st July, 2017

Laravelephant left a reply on Structure Question • 4 months ago

Awesome, thanks :D

30th July, 2017

Laravelephant left a reply on Yet Another MacBook Pro Vs Air Exp Thread • 4 months ago

I use a MBA 13" on a daily basis and have a similar setup in terms of apps.

I've not had an issue with it, other than the fact that coding on a small screen can become quite tiring. I think that as long as you can hook it up to an external monitor or two then you're good to go.

Probably the ergonomics aren't great over the long term and an external keyboard/mouse would be better. But for portability and reliability I think they're great :)

28th July, 2017

Laravelephant left a reply on Shape My Blog Post With Facebook, And Other Social Medias • 4 months ago

No, I just searched for a relevant package. It looks simple to work with however.

27th July, 2017

Laravelephant left a reply on Shape My Blog Post With Facebook, And Other Social Medias • 4 months ago

Maybe a package like this? Just include it in your view

https://github.com/faustbrian/Laravel-Social-Share

Laravelephant left a reply on Structure Question • 4 months ago

Laravelephant left a reply on Structure Question • 4 months ago

@bashy - thanks, now done! Good suggestion!

@phpMick - Awesome I'd never heard of that tool before. Will give it a go :)

Laravelephant started a new conversation Structure Question • 4 months ago

Hi all

So I'm pretty confident that I'm coding something in the correct way, but would appreciate any feedback in case there's a better way of doing things.

I'm currently making a system where a user can book lessons. There are many types of lessons and these can repeat over a given period. For example a lesson might be on a Tuesday and a Friday every week for six weeks.

My structure is as follows:

Lesson has many Sessions Lesson has many Students

Session has many Students Session belongs to Teacher Session has many SessionDates

SessionDates belongs to Session

Student belongs to one Session Student belongs to one Lesson

Teacher has many Sessions

So the idea is that a Lesson acts kind of like a category. The user then provides the desired Session and based on the form they submit, my Controller will eventually use Carbon to loop over the dates and create entries in the 'session_dates' table which has the session_id and the date.

So essentially I'm using logic to create a separate DB entry for each session in the given time period. Session can then access the SessionDates, and Lesson can access all of its sessions.

The Session contains the lesson_id and teacher_id.

The Student is assigned to a lesson and a session.

Does that make sense, and is there a better way of doing this or does my method make sense?

Thanks!

26th July, 2017

Laravelephant left a reply on Best Way To Redirect With Values • 4 months ago

That's it working, both methods suggested are great.

Thanks both, I think I've been staring at my code too long as that was simple!

Laravelephant started a new conversation Best Way To Redirect With Values • 4 months ago

Ok so on the face of it, this is a simple question but I'd value any feedback.

I've currently created a form which posts to a controller method. The method then saves the data using:

Person::create(request()->all());

This works fine, but I then want to redirect the user to a payment page. The payment page needs to have the person name and id.

I can store the name in the session and flash it to the view, but can't pull the person's database ID and also flashing the session seems a little ungainly.

What would be the best way of redirecting with the data?

Thanks

3rd March, 2017

Laravelephant left a reply on Can I Get The Current Users Id From A Session? • 9 months ago

Couldn't you just pass the user to the controller and do

Auth::user()->id

?

Laravelephant started a new conversation Create Image/pdf From View • 9 months ago

I'm tearing my hair out with this one!

So I've created a view and want to export it to a PDF or preferably an SVG. The view is made up of HTML, JS and CSS including Bootstrap and custom styles.

I've tried snappy, dompdf and a few others and none of the PDFs render properly. Additionally I've tried Spatie's PhantomJS screenshot package but as I'm passing an authenticated user's data, it just screenshots the 'you need to be logged in page'.

Does anyone have any tips on how I can export a view in hi-res to PDF/SVG?

Thanks!

2nd March, 2017

Laravelephant left a reply on Display Polyline In Mapbox • 9 months ago

Works perfectly, thanks!

Laravelephant started a new conversation Display Polyline In Mapbox • 9 months ago

Hey

So I've been experimenting with creating custom maps using the Google Maps API. I've been successful in creating static maps with an encoded polyline.

Unfortunately, Google Maps has a watermark in its static maps which I don't want. It seems that Mapbox doesn't have this watermark and so I'm trying to create a map with a polyline.

From looking at the API docs, it doesn't look like they support creating a map with a polyline and instead want co-ordinates. I've now got an array of data that looks like this:

-3.721921,
40.420988,
-3.721936,
40.421034,
-3.721953,
40.421078,
-3.721985,
40.421122,
-3.722021,
40.421148,

MapBox wants the data in this format:

[38.893596444352134, -77.0381498336792],
    [38.89337933372204, -77.03792452812195],
    [38.89316222242831, -77.03761339187622],
    [38.893028615148424, -77.03731298446655],
    [38.892920059048464, -77.03691601753235],
    [38.892903358095296, -77.03637957572937],
    [38.89301191422077, -77.03592896461487],
    [38.89316222242831, -77.03549981117249],
    [38.89340438498248, -77.03514575958252],
    [38.893596444352134, -77.0349633693695]

Is there a way of converting the data I've put above into an acceptable format? I don't have any array keys etc to play with.

Alternatively, if someone knows how to create a Mapbox map with a polyline then that would be very helpful!

Thanks!

26th February, 2017

Laravelephant left a reply on Iterating Over A Large Loop • 9 months ago

@Snapey So (and this may be an ignorant question) if I'm rendering a view from the controller and the sole portion of the view are the images then you're saying that it's possible to queue the API calls within the loop and then pass the results to the view?

Edit Your Profile
Update

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