Adamcy_Cooler

Member Since 3 Months Ago

Experience Points
530
Total
Experience

4,470 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
0
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    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 Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

  • Community Pillar

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

Level 1
530 XP
Jan
15
1 week ago
Activity icon

Replied to Is It There A Way To Use One URI For Multiple Routes?

Wow!!! You are a genius, it worked, I used one controller and then use condition to check for a unique variable in the payload. Thank you a million times.

Jan
14
1 week ago
Activity icon

Started a new Conversation Is It There A Way To Use One URI For Multiple Routes?

I am using paystack payment gateway to receive a response using a callback function in my controller if the payment is successful, I have two ways to make payment on the site, one is through the site's store/shop and one through donation, which is working fine with a single route URI name which is /paystack/callback, the problem is when tried to use the same URI name to receive donation payment response it doesn't work, and when I check the route list only one URI with the name paystack/callback is listed.

This is my Route

// PAYMENT PROCESSING AND RETURN RESPONSE

 Route::post('/pay', '[email protected]')->name('payment');
 Route::get('/payment/callback', '[email protected]');

// DONATION PAYMENT PROCESSING AND RETURN RESPONSE

 Route::get('/donation', function () {  return view('donation'); })->name('donation');
 Route::post('/donation', '[email protected]')->name('donate');
 Route::get('/payment/callback', '[email protected]');

so my question is, is there a way to use that URI name for both payment response because that is the URI I used on the payment gateway website in my dashboard

Nov
28
1 month ago
Activity icon

Started a new Conversation How Do I Remove Double Quotes From Summitted Input Data

I have a form that submitted a generated reference number to the controller but it's submitted as string with "" when I retrieve it from the controller to use it

   $ref = $request->reference

the number is retrieved as

   $ref = "ET26295957"

so how can I remove the double quote and store it in a variable as

   $ref = ET26295957

Please anyone with an idea how to achieve this help

Nov
24
1 month ago
Activity icon

Replied to Stripe Webhook Event Not Updating On Subscription Table In Database

Yes sir I configured it on the control panel/dashboard and added the endpoint in the VerifyCsrfToken

        class VerifyCsrfToken extends Middleware
   {
         /**
         * The URIs that should be excluded from CSRF verification.
          *
         * @var array
         */
          protected $except = [
         'http://laravel-tests/vendor/stripe/stripe-php/lib/Webhook',
      ];


    }
Activity icon

Started a new Conversation Stripe Webhook Event Not Updating On Subscription Table In Database

I am testing stripe webhook with wamp server with laravel cashier, I am using stripe CLI to test but when I set my endpoint for stripe to listen

Stripe listen --forward-to http://laravel-tests/vendor/stripe/stripe-php/lib/Webhook

and fired up an event like new subscription, deleting, updating subscription it all post status 200, but the problem is when I canceled, update it doesn't reflect in subscription table in the database, I don't know what I did wrong if you know, please help.

but when I canceled my subscription from my app, it shows on the stripe dashboard but any event that occurred on the dashboard doesn't reflect on the database. is it the endpoint that was wrong or am I missing something?

this is the respons from stripe CLI

2020-11-24 07:37:24 --> setup_intent.created [evt_1Hqv9OLzAo4pwMcy1jw5GVcy] 2020-11-24 07:37:24 <-- [200] POST http://laravel-tests/vendor/stripe/stripe-php/lib/Webhook [evt_1Hqv9OLzAo4pwMcy1jw5GVcy] 2020-11-24 07:38:06 --> setup_intent.succeeded [evt_1HqvA9LzAo4pwMcyl4WlzxeW] 2020-11-24 07:38:06 <-- [200] POST http://laravel-tests/vendor/stripe/stripe-php/lib/Webhook [evt_1HqvA9LzAo4pwMcyl4WlzxeW] 2020-11-24 07:38:08 --> payment_method.attached [evt_1HqvACLzAo4pwMcyYt5dXxOd] 2020-11-24 07:38:08 <-- [200] POST http://laravel-tests/vendor/stripe/stripe-php/lib/Webhook [evt_1HqvACLzAo4pwMcyYt5dXxOd] 2020-11-24 07:38:09 --> customer.updated [evt_1HqvACLzAo4pwMcy26i3asDf] 2020-11-24 07:38:09 <-- [200] POST http://laravel-tests/vendor/stripe/stripe-php/lib/Webhook [evt_1HqvACLzAo4pwMcy26i3asDf] 2020-11-24 07:38:10 --> charge.succeeded [evt_1HqvAELzAo4pwMcyieotO6QR] 2020-11-24 07:38:10 <-- [200] POST http://laravel-tests/vendor/stripe/stripe-php/lib/Webhook [evt_1HqvAELzAo4pwMcyieotO6QR] 2020-11-24 07:38:10 --> invoice.created [evt_1HqvAELzAo4pwMcy5zC26m37] 2020-11-24 07:38:10 <-- [200] POST http://laravel-tests/vendor/stripe/stripe-php/lib/Webhook [evt_1HqvAELzAo4pwMcy5zC26m37] 2020-11-24 07:38:11 --> invoice.finalized [evt_1HqvAELzAo4pwMcywpBARbkd] 2020-11-24 07:38:11 <-- [200] POST http://laravel-tests/vendor/stripe/stripe-php/lib/Webhook [evt_1HqvAELzAo4pwMcywpBARbkd] 2020-11-24 07:38:11 --> invoice.paid [evt_1HqvAELzAo4pwMcyJqxgbJXE] 2020-11-24 07:38:11 <-- [200] POST http://laravel-tests/vendor/stripe/stripe-php/lib/Webhook [evt_1HqvAELzAo4pwMcyJqxgbJXE] 2020-11-24 07:38:11 --> invoice.payment_succeeded [evt_1HqvAELzAo4pwMcyRE6vDNpN] 2020-11-24 07:38:11 <-- [200] POST http://laravel-tests/vendor/stripe/stripe-php/lib/Webhook [evt_1HqvAELzAo4pwMcyRE6vDNpN] 2020-11-24 07:38:11 --> payment_intent.created [evt_1HqvAFLzAo4pwMcyGkCDthla]

Nov
21
2 months ago
Activity icon

Started a new Conversation Unrecognized Request URL (GET: /v1/customers/). If You Are Trying To List Objects, Remove The Trailing Slash

Please if anyone has any idea why I keep getting this error when I submitted the stripe subscription form should please help, this error got me stuck for a while now, just trying to create a subscription from the pricing page or subscription plan page, I have the plans stored in my database in a model called Plan. so what I want is for users to select a pricing plan monthly or yearly and it will take them to the payment page where they can make payment and activate a subscription. I am using Laravel Cashier with stripe.

Full error message Unrecognized request URL (GET: /v1/customers/). If you are trying to list objects, remove the trailing slash. If you are trying to retrieve an object, make sure you passed a valid (non-empty) identifier in your code. Please see https://stripe.com/docs or we can help at https://support.stripe.com/.

The Plans Model 

     public function up()
      {
    Schema::create('plans', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->string('identifier')->unique;
        $table->string('stripe_id')->unique;
        $table->timestamps();
    });
   }

The Route

Route::group(['namespace' => 'Subscriptions'], function() {
Route::get('plans', '[email protected]')->name('plans');
Route::get('/payments', '[email protected]')->name('payments');
Route::post('/payments', '[email protected]')->name('payments.store');
});

The Plans page

<div class="container">
   <div class="row justify-content-center">
   <div class="col-md-8">
       <div class="card">
        <div class="card-header">{{ __('Subscription Plans') }}</div>

        <div class="card-body">
            @foreach($plans as $plan)
                <div>
                    <a href="{{ route('payments', ['plan' => $plan->identifier]) }}">{{$plan->title}}</a>
                    {{-- {{dd($plan->stripe_id)}} --}}
                </div>
            @endforeach
            </div>
         </div>
      </div>
    </div>
  </div>
This is The Form

<form action="{{ route('payments.store')}}" method="POST" id="payment-form">
@csrf
 <div class="form-content">


<input type="hidden" name="plan" id="subscription-plan" value="{{ request('plan') }}">

<div class="field">
  <input type="text" autocorrect="off" spellcheck="false" id="card-holder-name" maxlength="25" />
  <span class="focus-bar"></span>
  <label for="cardholder">Card holder (Name on card)</label>
</div>
    
    <div  class="field mb-5" id="card-element">
    <!-- Stripe Elements Placeholder -->
    </div>

   <button id="card-button" type="submit" data-secret="{{ $intent->client_secret }}"> 
   <span>Pay</span></button></div>
    </form>



 This is the PaymentsController

    public function index()
  {


   $user = auth()->user();

     $data = [
    'intent' => $user->createSetupIntent(),

  ];

return view('subscriptions.payments')->with($data);
 }

     public function store(Request $request)
 {


$user = auth()->user();

$paymentMethod = $request->payment_method;

$plan = Plans::where('identifier', $request->plan)
    ->orWhere('identifier', 'basic_product')
    ->first();

$request->user()->newSubscription('default', $plan->stripe_id)->create($paymentMethod);


return response(['status' => 'success']);
 }

This is the JavaScript

     / / Create a Stripe client.
           const stripe = Stripe('pk_test_51H2OqqLzAo4pwMcyT4h405wpFRAn3FWhvByfvmVnW6tabrIsDoU1dBXJ0UaWexUJeacCJ9uKpb 
      5OBmmA2KaCg4sd00ZZ5tj2q8');

        // Create an instance of Elements.
         const elements = stripe.elements();

        // Custom styling can be passed to options when creating an Element.
         // (Note that this demo uses a wider set of styles than the guide below.)
     
         // const cardElement = elements.create('card', {style: style});
     
    

          / / Create an instance of the card Element.
          const cardElement = elements.create('card');

        // Add an instance of the card Element into the `card-element` <div>.
         cardElement.mount('#card-element');

            const cardHolderName = document.getElementById('card-holder-name');
            const cardButton = document.getElementById('card-button');
            const clientSecret = cardButton.dataset.secret;

           const plan = document.getElementById('subscription-plan').value;


         // Handle form submission.
        var form = document.getElementById('payment-form');
        form.addEventListener('submit', async (e) => {
         e.preventDefault();
       
          cardButton.disabled = true
           const { setupIntent, error } = await stripe.confirmCardSetup(
            cardButton.dataset.secret, {
                payment_method: {
                    card: cardElement,
                    billing_details: {
                        name: cardHolderName.value
                    }
                 }
              }
         
             );
           
                if (error) {
                // Display "error.message" to the user...
                } else {
              
            
               var paymentMethod  = setupIntent.payment_method;

        

                var form = document.getElementById('payment-form');
                var hiddenInput = document.createElement('input');
                hiddenInput.setAttribute('type', 'hidden');
                hiddenInput.setAttribute('name', 'payment_method');
                hiddenInput.setAttribute('value', paymentMethod);
                form.appendChild(hiddenInput);

                // Submit the form
                form.submit();

  
                 }
Nov
18
2 months ago
Activity icon

Awarded Best Reply on This Customer Has No Attached Payment Source Or Default Payment Method.

Adding a hidden input field in the form and setting the value to setupIntent.payment_method passed the payment_method id to the controller which is used to create the subscription so the problem is solved.

A few modifications and adding a hidden input field to the JS

        // Handle form submission.
              var form = document.getElementById('payment-form');
              form.addEventListener('submit', async (e) => {
              e.preventDefault();
            //cardButton.addEventListener('click', async (e) => {
                   //e.preventDefault()
                const { setupIntent, error } = await stripe.handleCardSetup(
                    clientSecret, cardElement, {
                        payment_method_data: { 
                        billing_details: { name: cardHolderName.value }
                        }
                    }
                );
               
                if (error) {
                    // Display "error.message" to the user...
                } else {
                    // The card has been verified successfully...
                   //console.log('handling success', setupIntent.payment_method);
                     axios.post('/subscribe',{
                     plan : plan
                })
                   var paymentMethod  = setupIntent.payment_method;

                    var form = document.getElementById('payment-form');
                    var hiddenInput = document.createElement('input');
                    hiddenInput.setAttribute('type', 'hidden');
                    hiddenInput.setAttribute('name', 'payment_method');
                    hiddenInput.setAttribute('value', paymentMethod);
                    form.appendChild(hiddenInput);

                    // Submit the form
                    form.submit();

      
                }
Activity icon

Replied to This Customer Has No Attached Payment Source Or Default Payment Method.

Adding a hidden input field in the form and setting the value to setupIntent.payment_method passed the payment_method id to the controller which is used to create the subscription so the problem is solved.

A few modifications and adding a hidden input field to the JS

        // Handle form submission.
              var form = document.getElementById('payment-form');
              form.addEventListener('submit', async (e) => {
              e.preventDefault();
            //cardButton.addEventListener('click', async (e) => {
                   //e.preventDefault()
                const { setupIntent, error } = await stripe.handleCardSetup(
                    clientSecret, cardElement, {
                        payment_method_data: { 
                        billing_details: { name: cardHolderName.value }
                        }
                    }
                );
               
                if (error) {
                    // Display "error.message" to the user...
                } else {
                    // The card has been verified successfully...
                   //console.log('handling success', setupIntent.payment_method);
                     axios.post('/subscribe',{
                     plan : plan
                })
                   var paymentMethod  = setupIntent.payment_method;

                    var form = document.getElementById('payment-form');
                    var hiddenInput = document.createElement('input');
                    hiddenInput.setAttribute('type', 'hidden');
                    hiddenInput.setAttribute('name', 'payment_method');
                    hiddenInput.setAttribute('value', paymentMethod);
                    form.appendChild(hiddenInput);

                    // Submit the form
                    form.submit();

      
                }
Activity icon

Awarded Best Reply on Image Saving In Database As C:\wamp64\tmp\phpAE1C.tmp Instead Of Saving In Public/images

Make these changes to the code and it's working now! Thank you!

     $input = $request->except('password', 'password_confirmation');


      to this,


      $input = $request->except('password', 'password_confirmation','image','avatar');

      if ($request->hasFile('image')) {
           $input['image'] = $ImageNameToStore;
   }

      if ($request->hasFile('avatar')) {
           $input['avatar'] = $filenameToStore;
   }
Activity icon

Replied to Image Saving In Database As C:\wamp64\tmp\phpAE1C.tmp Instead Of Saving In Public/images

Make these changes to the code and it's working now! Thank you!

     $input = $request->except('password', 'password_confirmation');


      to this,


      $input = $request->except('password', 'password_confirmation','image','avatar');

      if ($request->hasFile('image')) {
           $input['image'] = $ImageNameToStore;
   }

      if ($request->hasFile('avatar')) {
           $input['avatar'] = $filenameToStore;
   }
Activity icon

Started a new Conversation Image Saving In Database As C:\wamp64\tmp\phpAE1C.tmp Instead Of Saving In Public/images

I am trying to edit/update an image in a user table, when I select a new image and submit the form the image name doesn't get stored in the database instead this C:\wamp64\tmp\phpAE1C.tmp get saved in the image column, I don't know why, Please help if u know why.

The UsersController

           public function update(Request $request, $id)
      {
            $request->validate([
            'name' => 'required|string|max:225',
            'email' => 'required|string|email|max:255|unique:users,email,'.auth()->id(),
             'password' => 'sometimes|nullable|string|min:6|confirmed',
           ]);

       $user = auth()->user();

         //Handle avatar Upload
          if ($request->hasFile('avatar')) {
        // Get filename with extention 
        $filenamewithExt = $request->file('avatar')->getClientOriginalName();
        // Get just filename
        $filename = pathinfo($filenamewithExt, PATHINFO_FILENAME);
        // Get just Extention
        $extention = $request->file('avatar')->getClientOriginalExtension();
        // Filename to store
        $filenameToStore = $filename.'_'.time().'.'.$extention;
        // Upload Image
        $path = $request->file('avatar')->storeAs('public/avatars', $filenameToStore);

    }

    if ($request->hasFile('avatar')) {
        
        $user->avatar = $filenameToStore;
  
       
    }

    //Handle image Upload

    if ($request->hasFile('image')) {
        // Get filename with extention 
        $ImageNameWithExt = $request->file('image')->getClientOriginalName();
        // Get just filename
        $ImageName = pathinfo($ImageNameWithExt, PATHINFO_FILENAME);
        // Get just Extention
        $Extentions = $request->file('image')->getClientOriginalExtension();
        // Filename to store
        $ImageNameToStore = $ImageName.'_'.time().'.'.$Extentions;
        // Upload Image
        $paths = $request->file('image')->storeAs('public/images', $ImageNameToStore);

    }

    if ($request->hasFile('image')) {
        
        $user->image = $ImageNameToStore;

        
    }
    
     $user->save();

    $input = $request->except('password', 'password_confirmation');

     if (!$request->filled('password')) {
           $user->fill($input)->save();

    return back()->with('success', 'Profile updated successfully!');
     }

      $user->password = bcrypt($request->password);
      $user->fill($input)->save();

        return back()->with('success', 'Profile and password updated successfully');
    }






      The image input field in edit blade file

       <div class="form-group col-md">
    
      <div class="custom-file">
      <input type="file" name="image" class="custom-file-input" id="customFile" >
      <label class="custom-file-label text-align-left" style="text-align:left;" 
      for="customFile">Choose file</label>
       </div>

       </div>
Nov
16
2 months ago
Activity icon

Started a new Conversation This Customer Has No Attached Payment Source Or Default Payment Method.

when I try to create a new subscription I get this error (This customer has no attached payment source or default payment method. ) so I checked the PaymentController with dd($paymentMethod) which returned null

so I don't know why the variable $paymentMethod in store method is returning NULL from the $request but the request, for the price is returning the price_id. Please any help is appreciated

but when console.log() setupIntent.payment_method it returned the payment_method in the console

here is my PaymentController

         public function index()
{
    $availablePlans = [
        'price_1HnIiLLzAo4pwMcyh2aGaznB'  => 'Monthly',
        'price_1HnJ2vLzAo4pwMcygQT66juk'  => 'Yearly',
        'price_1HnIhILzAo4pwMcy9iH3j30L'  => 'Free Membership'
    ];

    $user = auth()->user();
    $data = [
        'intent' => $user->createSetupIntent(),
        'plans' =>  $availablePlans

    ];
    
    return view('payments.checkout')->with($data);
}
     

       public function store(Request $request)
    {

  


             $user = auth()->user();

              $paymentMethod = $request->payment_method;
             //  dd($paymentMethod);
    
    
             $planId = $request->plan;

             $user->newSubscription('premium', $planId)->create($paymentMethod);

             return response(['status' => 'success']);
       }

This is the Javascript

         window.addEventListener('load', function (){


      // Create a Stripe client.
        const stripe = Stripe('pk_test_51H2OqqLzAo4pwMcyT4h405wpFRAn3FWhvByfvmVnW6tabrIsDoU1dBXJ0UaWexUJeacCJ9uKpb5OBmmA2KaCg4sd00ZZ5tj2q8');

        // Create an instance of Elements.
        const elements = stripe.elements();

        // Custom styling can be passed to options when creating an Element.
        // (Note that this demo uses a wider set of styles than the guide below.)
         
         // const cardElement = elements.create('card', {style: style});

        // Create an instance of the card Element.
        const cardElement = elements.create('card');

        // Add an instance of the card Element into the `card-element` <div>.
        cardElement.mount('#card-element');

            const cardHolderName = document.getElementById('card-holder-name');
            const cardButton = document.getElementById('card-button');
            const clientSecret = cardButton.dataset.secret;

            const plan = document.getElementById('subscription-plan').value;

            cardButton.addEventListener('click', async (e) => {
                const { setupIntent, error } = await stripe.handleCardSetup(
                    clientSecret, cardElement, {
                        payment_method_data: { 
                        billing_details: { name: cardHolderName.value }
                        }
                    }
                );

                if (error) {
                    // Display "error.message" to the user...
                } else {
                    // The card has been verified successfully...
                   // console.log('handling success', setupIntent.payment_method);

                    axios.post('/subscribe', {
                      payment_method: setupIntent.payment_method,
                      plan: plan
                    })
                }
            });

         });                  

here is the form

         <form action="{{ route('subscribe')}}" method="POST" id="">
@csrf
  <div class="form-content">

      <div class="field">
        <select class="form-control" name="plan" id="subscription-plan">
          @foreach ($plans as $key=>$plan )
            <option value="{{$key}}">{{$plan}}</option>
          @endforeach
        </select>
      </div>

    <div class="field">
      <input type="text" autocorrect="off" spellcheck="false" id="card-holder-name" maxlength="25" />
      <span class="focus-bar"></span>
      <label for="cardholder">Card holder (Name on card)</label>
    </div>
        
        <div  class="field mb-5" id="card-element">
        <!-- Stripe Elements Placeholder -->
        </div>

    <button id="card-button" data-secret="{{ $intent->client_secret }}"><span>Pay</span></button>
    
  </div>
</form>

The Route

     Route::resource('payments', 'PaymentsController', [
         'names'=> [
              'index'     => 'checkout',
               'store'     => 'subscribe',
   
          ]
      ]);
Nov
09
2 months ago
Activity icon

Replied to Sharing Data To Multiple Views With One Controller

okay, thank you do u any suggestions?

Nov
07
2 months ago
Activity icon

Replied to Sharing Data To Multiple Views With One Controller

Thank you all for your reply I found this solution to work fine

Route::get('users/{id}', '[email protected]')->name('profile');

Route::get('Category/{id}', '[email protected]')->name('category');

CategoryController.php

       public function show($request, $id) {
        $category = Category::find($id);

        $users = $category->user;
        if ($request::route()->getName() == 'category') {
            return view('categories.show')->with('users', $users);
         } else {
            return view('profile.show')->with('users', $users);
         }
    }
Nov
05
2 months ago
Activity icon

Replied to Sharing Data To Multiple Views With One Controller

public function boot() {

       View::composer('*', function ($view) {

       $category = Category::find($id);

       $users = $category->user;

      return view('categories.show')->with('users', $users);
     });
    }
Activity icon

Started a new Conversation Sharing Data To Multiple Views With One Controller

Please I need to know if there is a way I can share data from one controller method to multiple views,

This is the CategoryController show method

/**

  • Display the specified resource.

  • @param int $id

  • @return \Illuminate\Http\Response */

                  public function show($id)
                {
                          $category = Category::find($id);
    
                            $users = $category->user;
    
                           return view('categories.show')->with('users', $users);
                 }
    

what I want is to share the same data with another page profile-display.blade.php without creating another controller.

Sep
27
3 months ago
Activity icon

Replied to Please How Do I Update Multiple Images In One-to-many Relationship

Thank you @a4ashraf for responding to my question but the article only shows how to make new upload/create not to update, but thank you appreciate it, man.

Activity icon

Started a new Conversation Please How Do I Update Multiple Images In One-to-many Relationship

I have two model Event and EventImages with One-To-Many relationship, I can upload many images linked to one event but the problem is when I tried to edit by updating all images linked to that event, which one only image is uploaded replacing all the other images, so my question is how can I update all the images related to that event all at once or individually? Please any help will be much appreciated.

Here is my Event Model

    class Event extends Model
{
     protected $fillable = ['title', 'date', 'time', 'venue', 'body'];

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

Event Migration

   public function up()
  {
   Schema::create('events', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->string('date');
    $table->string('time');
    $table->string('venue');
    $table->mediumText('body');
    $table->timestamps();
   });
  }

This is EventImage Model

class EventImage extends Model
{

protected $fillable = ['images', 'caption','event_id'];

public function event()
{
   return $this->belongsTo('App\Event');
}

}

EventImage migration

       public function up()
   {
      Schema::create('event_images', function (Blueprint $table) {
       $table->id();   
       $table->string('images');
       $table->string('caption');
       $table->integer('event_id')->unsigned();
       $table->foreign('event_id')->references('id')->on('events')
       ->onDelete('cascade');
       $table->timestamps();
    });
  }

The View edit page

    <div class="container mt-5" style="width:700px">
  <h2>CREATE EVENT</h2>
  <form class="" action="{{ route('updateevent', $event->id)}}" method="post" 
  enctype="multipart/form-data">
  @csrf
  {{method_field('PUT')}}

    <div class="form-group">
      <label for="title">Title</label>
      <input class="form-control" type="text" name="title" value="{{$event- 
     >title}}">
    </div>

    <div class="form-group ">
    <label  class="" for="date">Date</label>
    <input class="form-control" id="date"  type="date" name="date" 
      placeholder="" value="{{$event->date}}">
    </div>

    <div class="form-group">
      <label for="time">Time</label>
      <input class="form-control" type="time" name="time" value="{{$event- 
      >time}}">
    </div>

    <div class="form-group">
      <label for="caption">Caption</label>
      <input  class="form-control" type="text" name="caption" value=" 
     {{$image->caption}}">
      </div>

      <div class="location-group">
      <label for="venue">Venue</label>
      <input class="form-control" type="text" name="venue" value="{{$event- 
     >venue}}">
    </div>

    <div class="form-group">
      <label for="body">Body</label>
      <textarea class="form-control" name="body" rows="8" cols="80">{{$event- 
     >body}}</textarea>
    </div>

    <div class="location-group">
      <label for="images">Uplada Image</label>
      <input multiple="multiple" class="form-control" type="file" 
     name="images[]" value="">
    </div>

      <input type="submit" name="submit" class="btn btn-primary" 
      value="Submit"/>
  </form>

This is the EventController

public function store(Request $request)
{


    //Handle File Upload
 if ($request->hasFile('images')) {

    $files = $request->file('images');
    // Get filename with extention 

    foreach($files as $file) {
    $filenamewithExt = $file->getClientOriginalName();
    // Get just filename
    $filename = pathinfo($filenamewithExt, PATHINFO_FILENAME);
    // Get just Extention
    $extension = $file->getClientOriginalExtension();
    // Filename to store
    $filenameToStore = $filename.'_'.time().'.'.$extension;
    // Upload Image
    $path = $file->storeAs('public/images', $filenameToStore);
    }
} else {
    $filenameToStore = 'noimage.jpg';
}



// Create EventImages
 $event = Event::create($request->all());

   foreach($request->images as $image) {

      $images = $image->store('images');
      $filenamewithExt = $image->getClientOriginalName();
// Get just filename
      $filename = pathinfo($filenamewithExt, PATHINFO_FILENAME);
// Get just Extention
      $extension = $image->getClientOriginalExtension();
// Filename to store
      $filenameToStore = $filename.'_'.time().'.'.$extension;
   EventImage::create([
    'event_id' => $event->id,
    'images'   => $filenameToStore,
    'caption'  => $request->caption,
    
  ]);
 }


public function update(Request $request, $id)
  {
            //Handle File Upload
 if ($request->hasFile('images')) {

    $files = $request->file('images');
    // Get filename with extention 

    foreach($files as $file) {
    $filenamewithExt = $file->getClientOriginalName();
    // Get just filename
    $filename = pathinfo($filenamewithExt, PATHINFO_FILENAME);
    // Get just Extention
    $extension = $file->getClientOriginalExtension();
    // Filename to store
    $filenameToStore = $filename.'_'.time().'.'.$extension;
    // Upload Image
    $path = $file->storeAs('public/images', $filenameToStore);
    }
} else {
    $filenameToStore = 'noimage.jpg';
}



// UPDATE EventImages
  $event = Event::find($id);
  $event->update($request->all());
  foreach($request->images as $image) {

$images = $image->store('images');
$filenamewithExt = $image->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenamewithExt, PATHINFO_FILENAME);
// Get just Extention
$extension = $image->getClientOriginalExtension();
// Filename to store
$filenameToStore = $filename.'_'.time().'.'.$extension;



$event->images()->update([
    'event_id' => $event->id,
    'images'   => $filenameToStore,
    'caption'  => $request->caption,
    
    ]);
   }
}
Activity icon

Started a new Conversation Images Update/edit In One-to-many Relationship

I have two model Event and EventImages with One-To-Many relationship, I can upload many images linked to one event but the problem is when I tried to edit by updating all images linked to that event, which one only image is uploaded replacing all the other images, so my question is how can I update all the images related to that event all at once or individually? Please any help will be much appreciated.

Here is my Event Model

    class Event extends Model
{
     protected $fillable = ['title', 'date', 'time', 'venue', 'body'];

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

Event Migration

   public function up()
  {
   Schema::create('events', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->string('date');
    $table->string('time');
    $table->string('venue');
    $table->mediumText('body');
    $table->timestamps();
   });
  }

This is EventImage Model

class EventImage extends Model
{

protected $fillable = ['images', 'caption','event_id'];

public function event()
{
   return $this->belongsTo('App\Event');
}

}

EventImage migration

       public function up()
   {
      Schema::create('event_images', function (Blueprint $table) {
       $table->id();   
       $table->string('images');
       $table->string('caption');
       $table->integer('event_id')->unsigned();
       $table->foreign('event_id')->references('id')->on('events')
       ->onDelete('cascade');
       $table->timestamps();
    });
  }

The View edit page

    <div class="container mt-5" style="width:700px">
  <h2>CREATE EVENT</h2>
  <form class="" action="{{ route('updateevent', $event->id)}}" method="post" 
  enctype="multipart/form-data">
  @csrf
  {{method_field('PUT')}}

    <div class="form-group">
      <label for="title">Title</label>
      <input class="form-control" type="text" name="title" value="{{$event- 
     >title}}">
    </div>

    <div class="form-group ">
    <label  class="" for="date">Date</label>
    <input class="form-control" id="date"  type="date" name="date" 
      placeholder="" value="{{$event->date}}">
    </div>

    <div class="form-group">
      <label for="time">Time</label>
      <input class="form-control" type="time" name="time" value="{{$event- 
      >time}}">
    </div>

    <div class="form-group">
      <label for="caption">Caption</label>
      <input  class="form-control" type="text" name="caption" value=" 
     {{$image->caption}}">
      </div>

      <div class="location-group">
      <label for="venue">Venue</label>
      <input class="form-control" type="text" name="venue" value="{{$event- 
     >venue}}">
    </div>

    <div class="form-group">
      <label for="body">Body</label>
      <textarea class="form-control" name="body" rows="8" cols="80">{{$event- 
     >body}}</textarea>
    </div>

    <div class="location-group">
      <label for="images">Uplada Image</label>
      <input multiple="multiple" class="form-control" type="file" 
     name="images[]" value="">
    </div>

      <input type="submit" name="submit" class="btn btn-primary" 
      value="Submit"/>
  </form>

This is the EventController

public function store(Request $request)
{


    //Handle File Upload
 if ($request->hasFile('images')) {

    $files = $request->file('images');
    // Get filename with extention 

    foreach($files as $file) {
    $filenamewithExt = $file->getClientOriginalName();
    // Get just filename
    $filename = pathinfo($filenamewithExt, PATHINFO_FILENAME);
    // Get just Extention
    $extension = $file->getClientOriginalExtension();
    // Filename to store
    $filenameToStore = $filename.'_'.time().'.'.$extension;
    // Upload Image
    $path = $file->storeAs('public/images', $filenameToStore);
    }
} else {
    $filenameToStore = 'noimage.jpg';
}



// Create EventImages
 $event = Event::create($request->all());

   foreach($request->images as $image) {

      $images = $image->store('images');
      $filenamewithExt = $image->getClientOriginalName();
// Get just filename
      $filename = pathinfo($filenamewithExt, PATHINFO_FILENAME);
// Get just Extention
      $extension = $image->getClientOriginalExtension();
// Filename to store
      $filenameToStore = $filename.'_'.time().'.'.$extension;
   EventImage::create([
    'event_id' => $event->id,
    'images'   => $filenameToStore,
    'caption'  => $request->caption,
    
  ]);
 }


public function update(Request $request, $id)
  {
            //Handle File Upload
 if ($request->hasFile('images')) {

    $files = $request->file('images');
    // Get filename with extention 

    foreach($files as $file) {
    $filenamewithExt = $file->getClientOriginalName();
    // Get just filename
    $filename = pathinfo($filenamewithExt, PATHINFO_FILENAME);
    // Get just Extention
    $extension = $file->getClientOriginalExtension();
    // Filename to store
    $filenameToStore = $filename.'_'.time().'.'.$extension;
    // Upload Image
    $path = $file->storeAs('public/images', $filenameToStore);
    }
} else {
    $filenameToStore = 'noimage.jpg';
}



// UPDATE EventImages
  $event = Event::find($id);
  $event->update($request->all());
  foreach($request->images as $image) {

$images = $image->store('images');
$filenamewithExt = $image->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenamewithExt, PATHINFO_FILENAME);
// Get just Extention
$extension = $image->getClientOriginalExtension();
// Filename to store
$filenameToStore = $filename.'_'.time().'.'.$extension;



$event->images()->update([
    'event_id' => $event->id,
    'images'   => $filenameToStore,
    'caption'  => $request->caption,
    
    ]);
   }
}