Joel  Hawkins

Joel Hawkins

1586943240

Call POST Method from Another Controller in Laravel

Preamble

Sometimes when developing systems, I sometimes come across cases that require calling a post method from another function in Laravel. These functions may or may not be in the same controller / class. Previously when handling these cases, my handling was rudimentary and handling this case made my code very confusing and made it difficult for others to read the code if I didn’t really understand the purpose of the paragraph. my code. After a while of researching, I also found a better way to handle this case, so today I will introduce you how to handle it when you have to call a post method from another function in laravel. .

Problem

Suppose you have a very complex method that takes one input parameter Illuminate\Http\Request $request. This method will normally be called from a form or an AJAX function. So how can you call that method from another method - even in another class?

To make the problem easier to imagine, I will go into specific code. The following is a very complex method that we initialize, and suppose we don’t want to have to fix it at all.

The Very Complex Method

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class VeryComplexController extends Controller
{
    public function __contruct()
    {
        //do constructor stuff
    }

    public function veryComplexMethod(Request $request)
    {
        //wow there is some very complex stuff in here
    }
}

VeryComplexController.php

Meanwhile we have another method that we want to call here veryComplexMethod()

The Simple Method

<?php

namespace App\Http\Controllers;

class SimpleController extends Controller
{
    public function __construct()
    {
        //do constructor stuff...
    }

    public function simpleMethod()
    {
        //we want to call veryComplexMethod() from here... but how?
    }
}

SimpleController.php

Simple handling

This is the way I used to, that we created a “Calling” function, copy the entire process code veryComplexMethodto another function that we can call from the current function. In essence, you will create a function to retrieve data from the post request and then call another function - this function is actually where the processing is done - by passing parameters from Request to. So now when it veryComplexMethodis called, it will extract the data from the Request and pass it on veryComplexMethodProcessing- this is the actual processing function.

<?php

public function veryComplexMethod(Request $request)
{
    $data = $request->all();
    return $this->veryComplexMethodProcessing($data);
}

public function veryComplexMethodProcessing($data)
{
    //process data....
    return $answer;
}

SolutionController.php

Advantages:

  • Don’t Repeat Yourself: You are following the DRY principle, you don’t need to rewrite any code.

Defect:

  • Refactor: You have to fix something and change some functions for your code to work.
  • Inconsistencies: Not all of your methods need this, which means that eventually you will have some functions that use the calling function while some don’t.
  • In case you have consistency and all your post methods use the “calling” function, you will increase the number of functions you have to handle.

Better handling

To handle the above drawbacks, create a class that can make a request that can excute any method we want and then simply pass that Request as a parameter. In other words, we will try to imitate what a form or an AJAX will do.

For example, I will create a class PostCaller

<?php

namespace App\Http;

class PostCaller
{ 
    /**
     * $class is the class where the method you will be calling is located.
     */
    public $class;

    /**
     * $method is the name of the method you want to call that exists inside of $class.
     */
    public $method;

    /**
     * $requestClass is the type of Request. You can use custom requests 
     * and don't have to use Illuminate\Http\Request.
     */
    public $requestClass;

    /**
     * $data is the data you are passing into the method. It should be an array with indexes
     * and values. No CSRF token is required.
     */
    public $data;

    /**
     * $requestSending is the actual request object you will be sending. You will attach the data to this.
     */
    public $requestSending;

    public function __construct($class, $method, $requestClass, $data)
    {
        //assign parameter values to class object
        $this->class = $class;
        $this->method = $method;
        $this->requestClass = $requestClass;
        $this->data = $data;

        //instantiate the request object and replace the data.
        $this->requestSending = new $this->requestClass();
        $this->requestSending->replace($this->data);
    }

    /**
     * Execute the method and return the response.
     * @return mixed
     */
    public function call()
    {
        $response = app($this->class)->{$this->method}($this->requestClass::createFromBase($this->requestSending));

        return $response;
    }
}

PostCaller.php

In this class we will define some parameters and pass in constructand finally the callfunction to handle calling a function and receiving a response.

This solution solves a number of problems that were not resolved previously.

  • First, it becomes a generic call function that works with any method that accepts a Request as input - in any class.
  • Second, it actually sends one Requestas a parameter, which may or may not matter to the function you are calling.
  • Third, you don’t need to refactor the method you’re trying to call. In the previous way we had to convert the word processing part Requestto the “calling” function and then pass the data over.

Let’s explain a bit about the method callofPostcaller

app($this->class)

Here we are creating a Laravel service container instance and binding it to the class you are choosing. There are several advantages to using a service container this way:

  • You do not need to use keywords new
  • It returns an instance of the class that you can use in just one line of code
  • You do not need to import class namespace into the scope of PostCallerthe keyworduse

Add to that the other benefits of service containers .

{$this->method}()

Call a specific method inside the class that we passed in. Using the syntax {}, we can automatically call a method. So, if our class is TestingClass::classand method is runTest, this will correspond to app(TestingClass::class)->{'runTest'}().

$this->requestClass::createFromBase($this->requestSending)

We create an Illuminate request from the Symfony Instance. We can pass in requestClass- maybe one, Illuminate\Http\Requestbut it can also be a custom FormRequest

return $response

We can then return any response that method returns to us. You can then use this response to process the returned data.

Finally, how to use. This is an example of usagePossCaller

<?php

namespace App\Http\Controllers;

use App\Http\PostCaller;
use Illuminate\Http\Request;
use App\Http\Controllers\VeryComplexController;

class SimpleController extends Controller
{
    public function __construct()
    {
        //do constructor stuff...
    }

    public function simpleMethod()
    {
        //we decide we would like to call veryComplexMethod() from here using PostCaller
        $post = new PostCaller(
            VeryComplexController::class,
            'veryComplexMethod',
            Request::class,
            [
                'Field1' => 'something',
                'Field2' => 'something else',
            ]
        );
        $response = $post->call();
        //do something with the response.
    }
}

SimpleController.php

summary

The above is a way we can call a method to get parameters Requestfrom another method in Laravel. There may be many other ways to do this, the above is just one of the ways I learn. Hopefully this approach can help you a little on your way to becoming a programmer with your mind and reach.

#php #laravel

What is GEEK

Buddha Community

Call POST Method from Another Controller in Laravel
Seamus  Quitzon

Seamus Quitzon

1595201363

Php how to delete multiple rows through checkbox using ajax in laravel

First thing, we will need a table and i am creating products table for this example. So run the following query to create table.

CREATE TABLE `products` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 `description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Next, we will need to insert some dummy records in this table that will be deleted.

INSERT INTO `products` (`name`, `description`) VALUES

('Test product 1', 'Product description example1'),

('Test product 2', 'Product description example2'),

('Test product 3', 'Product description example3'),

('Test product 4', 'Product description example4'),

('Test product 5', 'Product description example5');

Now we are redy to create a model corresponding to this products table. Here we will create Product model. So let’s create a model file Product.php file under app directory and put the code below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'name','description'
    ];
}

Step 2: Create Route

Now, in this second step we will create some routes to handle the request for this example. So opeen routes/web.php file and copy the routes as given below.

routes/web.php

Route::get('product', 'ProductController@index');
Route::delete('product/{id}', ['as'=>'product.destroy','uses'=>'ProductController@destroy']);
Route::delete('delete-multiple-product', ['as'=>'product.multiple-delete','uses'=>'ProductController@deleteMultiple']);

#laravel #delete multiple rows in laravel using ajax #laravel ajax delete #laravel ajax multiple checkbox delete #laravel delete multiple rows #laravel delete records using ajax #laravel multiple checkbox delete rows #laravel multiple delete

Fredy  Larson

Fredy Larson

1595205933

Laravel create model migration and controller in a single command

Hello guys, sometimes while working on the large application, we need to create some very small modules like simple CRUD. So here in this article i will let you know laravel create model migration and controller in a single command.

We will run a single artisan command to create model. migration and controller. We can also create resource controller by giving parameter.

We can these model, migration and controller from three command but for time saving laravel provides feature to create thses three thing by one single command.

So for desired result open your terminal and run the following command.

php artisan make:model --migration --controller Product --resource  

Here, we have create product model, migration and product controller with all the resources methods.

We can also write this command in the short form like below.

php artisan make:model -mc Product --resource

You can also write this command in a more short way like below.

php artisan make:model Product -mcr

**Note: **Here, m represents migration, c represents controller and r represents as resource.

After running the above command you will get the output like

Model created successfully

Created migration (migration file name with current date and migration name )

Controller created successfully.

You can also read the article to create to add a column in the existing table through migration by clicking on the link below.

#laravel #create controller resource and model in a command #laravel artisan command #laravel create model #laravel single command for model and migration #migration and controller

sophia tondon

sophia tondon

1618970788

Top Laravel Development Company India | Laravel Development Services

Laravel is a popular framework for website development, acquiring 25.85% of the PHP framework market share. As a most admired framework among PHP frameworks, it is being utilized for e-commerce, enterprise, social media, and various different types of websites.

There are more than 1 million websites worldwide available over the web that are created using Laravel. Laravel framework is the first preference of PHP developers as it allows them to develop highly scalable, flexible, and faster web applications.

Surely, you, too, would want to deliver a splendid and unhindered user experience to your target audience over the web. Laravel framework can help you achieve this pursuit at ease; all you need to do is hire Laravel developers from reliable & coveted hosts. But! There is no shortage of Laravel development companies that promise to deliver an excellent solution, but only some are able to deliver top-notch quality.

Therefore, I have decided to enlist top Laravel development companies to help you find a reliable and expert host for web development. So, stay hooked with me till the end of this article and explore the best Laravel developers in 2021.

While creating this list, I have kept the following pointers in reflection:

Years of excellence (average 8 years)
Workfolio
Rewards & Recognition
Client rating & feedback
Hourly/Monthly Price
Number of happy clients
Number of successfully launched projects
Minimum man-years experience
So, let’s not waste a minute and glance at top Laravel development companies to hire for creating excellent web solutions.

Read More - https://www.valuecoders.com/blog/technology-and-apps/top-laravel-development-companies-to-hire-experts/

#hire a laravel developer #hire laravel developer #hire laravel developers #laravel developer for hire #laravel developers #laravel developers for hire

Yogi Gurjar

1600307723

Laravel 8 Form Example Tutorial - Complete Guide

Laravel 8 form example. In this tutorial, i would love to show you how to create form in laravel. And how to insert data into database using form in laravel 8.

How to Submit Form Data into Database in Laravel 8

  1. Step 1 – Install Laravel 8 Application
  2. Step 2 – Configuring Database using Env File
  3. Step 3 – Create Model & Migration File For Add Blog Post Form
  4. Step 4 – Create Routes
  5. Step 5 – Creating Controller
  6. Step 6 – Create Blade File For Add Blog Post Form
  7. Step 7 – Start Development Server
  8. Step 8 – Run Laravel 8 Form App On Browser

https://laratutorials.com/laravel-8-form-example-tutorial/

#insert form data into database using laravel #laravel bootstrap form #laravel post forms #laravel 8 form tutorial #laravel 8 form example #laravel 8 form submit tutorial

sophia tondon

sophia tondon

1620977020

Hire Laravel Developers | Laravel Development Company, Services India

Looking for a team of experienced offshore Laravel developers? Hire a top dedicated team of Laravel developers from India online with 6+ years of average experience on an hourly or dedicated (monthly) basis from ValueCoders and enjoy easy hiring, quality work, and on-demand scalability at up to 60% less cost.

Our offshore Laravel development experts are fully competent to build scalable, secure, and robust custom web apps suiting your business requirements.

First Time Right Process
Complete Control Over The Team
Certified Laravel Coders
Agile & DevOps Enablement
Non-Disclosure Agreement
No Contract Lock-Ins

Visit Us- https://www.valuecoders.com/hire-developers/hire-laravel-developers

#hire a laravel developer #hire laravel developer #laravel development #hire laravel experts #find laravel developers #laravel development services india