Laravelephant

Experience

10,170

3 Best Reply Awards

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

12th October, 2017

Laravelephant left a reply on Submit Form With Multiple Values • 6 days 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 • 6 days 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 • 6 days 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 • 6 days 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 • 1 week ago

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

Laravelephant started a new conversation Save Data Cleanly • 1 week 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 • 3 weeks 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 • 3 weeks 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 • 3 weeks 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 • 3 weeks 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 • 2 months ago

Awesome, thanks :D

30th July, 2017

Laravelephant left a reply on Yet Another MacBook Pro Vs Air Exp Thread • 2 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 • 2 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 • 2 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 • 2 months ago

Laravelephant left a reply on Structure Question • 2 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 • 2 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 • 2 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 • 2 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? • 7 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 • 7 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 • 7 months ago

Works perfectly, thanks!

Laravelephant started a new conversation Display Polyline In Mapbox • 7 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 • 7 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?

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

Hey @Snapey - if I'm using the call to render images to a user in a view would a job still be appropriate?

@lars6 - Chunk could be interesting. Will give it a go!

25th February, 2017

Laravelephant started a new conversation Iterating Over A Large Loop • 7 months ago

Hey

So I've got a loop over about 500 items which I'm iterating over in a foreach loop and doing an API call in this loop. So far it's very slow and crashes when over a certain size. Does anyone have any tips on optimising this?

Code:

$image_url = array();
  foreach ($pictures as $picture) {
    try {
      $grabUrl = Media::get($picture);
      $grabUrl = json_decode($grabUrl, true);
      $image_url[] = $grabUrl['data'];
    } 
  }

13th November, 2016

Laravelephant left a reply on Redirect To Homepage After Password Reset • 11 months ago

You're completely correct, thanks :)

Laravelephant left a reply on Redirect To Homepage After Password Reset • 11 months ago

Just add

protected $redirectTo = 'VIEW';

In the ResetPasswordController. See the docs: https://laravel.com/docs/master/passwords#after-resetting-passwords

Laravelephant left a reply on Stripe • 11 months ago

Documentation on Stripe should sort you out: https://support.stripe.com/questions/can-a-customer-have-multiple-credit-cards-on-file

https://stripe.com/docs/api#cards

Just add the cards and then charge the relevant one.

3rd November, 2016

Laravelephant left a reply on Storing Array Data In Laravel • 11 months ago

Haha! That works perfectly, thanks so much!

Agreed re the variable name and I'm going to study this a bit more till I get to grips with it. Thanks :)

Laravelephant left a reply on Storing Array Data In Laravel • 11 months ago

That makes perfect sense and thanks for the heads up on the typo! Code ought to be working now but I'm getting a 500 error stating that 'array' is null and so the foreach fails.

My guess is that the ajax script isn't passing the data in that case?

Laravelephant left a reply on Storing Array Data In Laravel • 11 months ago

D'oh! Stupid typo, corrected that but still nothing being inserted!

I can't think of any reason at all - there are no errors, the table name and field names are correct, the data is being posted. What gives?

Laravelephant left a reply on Storing Array Data In Laravel • 11 months ago

I'm probably explaining this badly! It's not passing the 'picture_id' from the ajax into the DB. Here's the function:

public function store(Request $request) {
    $storePicture = new PicturePrice;
    $images = $request->get('array');

    for($i = 0; $i < count($image); $i++) {
      $storePicture->picture_id = $i;
      $storePicture->picture_owner = Auth::user()->id;
      $storePicture->price = '10';
      $storePicture->save();
    }
  }

Ajax is:

<script>
        $(document).ready(function() {
          $.ajaxSetup({
            headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $(".user-images" ).click(function() {
            $( this ).toggleClass( 'selected');
        });

        $( "#saveImages" ).click(function() {
            let array = [];
            $(".selected").each(function() {
              array.push($(this).attr("data-picture-key"));
            });
            console.log(array);
            $.ajax({
             type: "POST",
              url: "images/add",
              data: array,
              success: function() {
                console.log('success');
              }
            });
          });
        });
        </script>

This logs success and spits out the image ids in the console and I get no errors, but when I check the DB, nothing is there.

Laravelephant left a reply on Storing Array Data In Laravel • 11 months ago

Hey

Thanks to everyone for the really helpful responses! All are coming back with 'success' but actually none are appearing in the database.

The model has the correct fillable fields and the code itself works fine - just nothing is actually being inserted...

Laravelephant left a reply on Storing Array Data In Laravel • 11 months ago

Ok it seems happy with that but what should I be putting as my picture_id on the insert query? $request->all()

?

Laravelephant started a new conversation Storing Array Data In Laravel • 11 months ago

Hey

I've currently got an ajax script which allows me to select pictures and grab their ID. It posts the ids as an array to my controller but I'm having issues working out how best to save it.

My db structure looks like

ID | picture_id | picture_owner

The data that my ajax script posts looks like:

Array[3] 0: "123" 1: "456" 2: "789"

I'm wanting each of these values to have their own row on the DB and post through the Auth::user()->id as well. How am I best dealing with the data in the controller?

Thanks!

17th October, 2016

Laravelephant left a reply on HasMany Through Relationship • 1 year ago

That makes total sense, thanks :)

Laravelephant started a new conversation HasMany Through Relationship • 1 year ago

Hi there

I'm currently designing a system which will have three models:

Landlord Tenant Property

This is on top of the usual User model. I'm wanting to create a relationship where:

Landlord has a property which has tenants. The tenant belongs to the property, and the property belongs to the landlord. I'd want the system to be such that a landlord could view their property and its tenants.

From what I've seen, a HasManyThrough relationship would be the best for this and I'd store 'property_id' in the Landlord table, 'landlord_id' in the Property table, and both 'landlord_id' and 'property_id' in the tenant table.

Any advice on how to structure the relationship and work with it would be appreciated. Thanks!

4th October, 2016

Laravelephant left a reply on Laravel Project Help • 1 year ago

Look into Eloquent Relationships: https://laravel.com/docs/5.3/eloquent-relationships

Sounds like you'll want the Office model to be something like:

public function office_user() {
        return $this->hasMany('App\OfficeUser');
}
 

and the OfficeUser model to be like:

public function office_user () {
        return $this-belongsTo('App\Office');
}

Obviously made up names but hopefully that gives you an idea.

30th August, 2016

Laravelephant left a reply on Using And Creating Dynamic Databases • 1 year ago

You're probably going to want to look into multi-tenant apps. There are a few tutorials around, also see the links below. Personally I'd just do separate tables rather than a separate DB but I guess it depends on your use case.

https://packagist.org/packages/hipsterjazzbo/landlord

http://culttt.com/2014/03/31/multi-tenancy-laravel-4/ (slightly out of date but similar principles)

Also, this thread may be useful: https://laracasts.com/discuss/channels/general-discussion/hitting-multiple-databases-dinamically-with-laravel

Laravelephant left a reply on Paypal Integration In Laravel • 1 year ago

Isn't that the response you receive after you post to Braintree?

29th August, 2016

Laravelephant left a reply on Paypal Integration In Laravel • 1 year ago

Doesn't Braintree accept Paypal? If so, then Cashier should cover you!

https://www.braintreepayments.com/payment-methods/accept-paypal

https://laravel.com/docs/5.3/billing

16th August, 2016

Laravelephant left a reply on Send An Email To Multple People • 1 year ago

Why not grab all the emails into an array, then run a foreach loop on that and send the email?

Like

foreach ($rsvps as $rsvp) {
//send mail to $rsvp->email
}

Laravelephant left a reply on File Validation - How To Set A Max File Size? • 1 year ago

Documentation should help: https://laravel.com/docs/5.2/validation#custom-error-messages

There's an example in their for validating filesize and giving a custom error message :)

21st July, 2016

Laravelephant left a reply on Send Welcome Email On User Registration • 1 year ago

Hmm

Why not do something like this:

return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => bcrypt($data['password']), $user = $data['email']; Mail::send('emails.welcome', $user, function($message) use ($user) { $message->from('[email protected]', 'xxxx.uk'); $message->subject("Welcome to xxxxx.me.uk"); $message->to($user; ]);

Laravelephant left a reply on Send Welcome Email On User Registration • 1 year ago

Do you have use Mail; in your controller?

24th April, 2016

Laravelephant left a reply on Blade Issues • 1 year ago

Hey @TerrePorter

Sorry, I probably didn't explain it well. I'm using $term in the view as the 'term' that I've got in my $data array in the controller.

So in my view I want to display each entry of '$list->name' and then the $list->link that's associated with it.

Laravelephant left a reply on Blade Issues • 1 year ago

Ok, got this a little more:

So I'm passing $val as my 'term'. This is an array of all the data ('data', 'user' and 'link'). I then do a foreach term as data within my view.

In the view, it's saying that I'm throwing it an array, even though I'm trying to access it like $data['name'] etc. Not sure why this is happening?

Laravelephant left a reply on Blade Issues • 1 year ago

So I'm passing term to the view and simply displaying it as shown above. From that I get the 'data' field from my array.

Weirdly $data['data'] definitely works but it still won't grab the link.

Laravelephant started a new conversation Blade Issues • 1 year ago

I'm sending an email with multiple values grabbed from the following array:

object(Illuminate\Support\Collection)[215]
  protected 'items' => 
    array (size=2)
      0 => 
        array (size=3)
          'data' => string 'My text' 
          'user' => string 'a.user@gmail.com'
          'link' => string 'http://google.com'
      1 => 
        array (size=3)
          'data' => string 'Test data' 
          'user' => string 'a.user@gmail.com'
          'link' => string 'https://twitter.com' 
object(Illuminate\Support\Collection)[216]
  protected 'items' => 
    array (size=1)
      0 => 
        array (size=3)
          'data' => string 'More test'
          'user' => string 'new.user@gmail.com'
          'link' => string 'https://facebook.com'

I'm fine sending an email to the separate users with the 'data' field so they would see the different entries. For some reason, I'm having issues accessing the 'link' value though.

Code looks like:

foreach($today as $list) { $names[] = ['data' => $list->name, 'user' => $list->email, 'link' => $list->link]; //foreach db result, add the data to our array }

    $names = collect($names)->groupBy('user'); 
    foreach($names as $name => $val) { 
      $link = array_pluck($val, 'link');
      $data =  array(
        'term' => $val,
        'link' => $link,
        'user' => $name,
        'from' => 'me@test.com',
      );

and in my blade:

@foreach ($term as $data)
        <li><a href="{{$data['link']}}">{{$data['data']}}</a></li>
@endforeach

I suspect I'm not passing the right value through but am having trouble getting this right!

Edit Your Profile
Update

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