Viewed   68 times

I can't figure out how to add a new column to my existing database table using the Laravel framework.

I tried to edit the migration file using...

<?php

public function up()
{
    Schema::create('users', function ($table) {
        $table->integer("paid");
    });
}

In terminal, I execute php artisan migrate:install and migrate.

How do I add new columns?

 Answers

1

To create a migration, you may use the migrate:make command on the Artisan CLI. Use a specific name to avoid clashing with existing models

for Laravel 3:

php artisan migrate:make add_paid_to_users

for Laravel 5+:

php artisan make:migration add_paid_to_users_table --table=users

You then need to use the Schema::table() method (as you're accessing an existing table, not creating a new one). And you can add a column like this:

public function up()
{
    Schema::table('users', function($table) {
        $table->integer('paid');
    });
}

and don't forget to add the rollback option:

public function down()
{
    Schema::table('users', function($table) {
        $table->dropColumn('paid');
    });
}

Then you can run your migrations:

php artisan migrate

This is all well covered in the documentation for both Laravel 3:

  • Schema Builder
  • Migrations

And for Laravel 4 / Laravel 5:

  • Schema Builder
  • Migrations

Edit:

use $table->integer('paid')->after('whichever_column'); to add this field after specific column.

Sunday, August 14, 2022
4

I don't see the reason, but I managed to make it on my local computer by php artisan make:model ../../mOdel . Probably in production environment you won't be allowed to do this.

Monday, November 21, 2022
 
claws
 
4

You can specify a mask for your {category} parameter so that it must fit the format "category[0-9]+" in order to match the route.

Route::get('/{category}/{region}/{suburb?}', 'SearchController@search')
    ->where('category', 'category[0-9]+');

Now, your example url (from the comments) www.a.com/var1/var2/var3 will only match the route if var1 matches the given category regex.

More information can be found in the documentation for route parameters here.

Edit

Yes, this can work with an array of string values. It is a regex, so you just need to put your array of string values into that context:

Route::get('/{category}/{region}/{suburb?}', 'SearchController@search')
    ->where('category', 'hairdresser|cooper|fletcher');

Or, if you have the array built somewhere else:

$arr = ['hairdresser', 'cooper', 'fletcher'];

// run each array entry through preg_quote and then glue
// the resulting array together with pipes
Route::get('/{category}/{region}/{suburb?}', 'SearchController@search')
    ->where('category', implode('|', array_map('preg_quote', $arr)));

Edit 2 (solutions for original request)

Your original question was how to pass the hardcoded category segment into the controller. If, for some reason, you didn't wish to use the solution above, you have two other options.

Option 1: don't pass the value in, just access the segments of the request in the controller.

public function search($region, $suburb = null) {
    $category = Request::segment(1);
    dd($category);
}

Option 2: modify the route parameters using a before filter (L4) or before middleware (L5).

Before filters (and middleware) have access to the route object, and can use the methods on the route object to modify the route parameters. These route parameters are eventually passed into the controller action. The route parameters are stored as an associative array, so that needs to be kept in mind when trying to get the order correct.

If using Laravel 4, you'd need a before filter. Define the routes to use the before filter and pass in the hardcoded value to be added onto the parameters.

Route::get('/hairdresser/{region}/{suburb?}', ['before' => 'shiftParameter:hairdresser', 'uses' => 'SearchController@search']);
Route::get('/cooper/{region}/{suburb?}', ['before' => 'shiftParameter:cooper', 'uses' => 'SearchController@search']);
Route::get('/fletcher/{region}/{suburb?}', ['before' => 'shiftParameter:fletcher', 'uses' => 'SearchController@search']);

Route::filter('shiftParameter', function ($route, $request, $value) {
    // save off the current route parameters    
    $parameters = $route->parameters();
    // unset the current route parameters
    foreach($parameters as $name => $parameter) {
        $route->forgetParameter($name);
    }

    // union the new parameters and the old parameters
    $parameters = ['customParameter0' => $value] + $parameters;
    // loop through the new set of parameters to add them to the route
    foreach($parameters as $name => $parameter) {
        $route->setParameter($name, $parameter);
    }
});

If using Laravel 5, you'd need to define a new before middleware. Add the new class to the app/Http/Middleware directory and register it in the $routeMiddleware variable in app/Http/Kernel.php. The logic is basically the same, with an extra hoop to go through in order to pass parameters to the middleware.

// the 'parameters' key is a custom key we're using to pass the data to the middleware
Route::get('/hairdresser/{region}/{suburb?}', ['middleware' => 'shiftParameter', 'parameters' => ['hairdresser'], 'uses' => 'SearchController@search']);
Route::get('/cooper/{region}/{suburb?}', ['middleware' => 'shiftParameter', 'parameters' => ['cooper'], 'uses' => 'SearchController@search']);
Route::get('/fletcher/{region}/{suburb?}', ['middleware' => 'shiftParameter', 'parameters' => ['fletcher'], 'uses' => 'SearchController@search']);

// middleware class to go in app/Http/Middleware
// generate with "php artisan make:middleware" statement and copy logic below
class ShiftParameterMiddleware {
    public function handle($request, Closure $next) {
        // get the route from the request
        $route = $request->route();

        // save off the current route parameters
        $parameters = $route->parameters();
        // unset the current route parameters
        foreach ($parameters as $name => $parameter) {
            $route->forgetParameter($name);
        }

        // build the new parameters to shift onto the array
        // from the data passed to the middleware
        $newParameters = [];
        foreach ($this->getParameters($request) as $key => $value) {
            $newParameters['customParameter' . $key] = $value;
        }

        // union the new parameters and the old parameters
        $parameters = $newParameters + $parameters;
        // loop through the new set of parameters to add them to the route
        foreach ($parameters as $name => $parameter) {
            $route->setParameter($name, $parameter);
        }

        return $next($request);
    }

    /**
     * Method to get the data from the custom 'parameters' key added
     * on the route definition.
     */
    protected function getParameters($request) {
        $actions = $request->route()->getAction();
        return $actions['parameters'];
    }
}

Now, with the filter (or middleware) setup and in use, the category will be passed into the controller method as the first parameter.

public function search($category, $region, $suburb = null) {
    dd($category);
}
Saturday, September 17, 2022
 
landys
 
2

If you check at the error trace:

Base table or view already exists: 1050 Table 'users' already exists

This means that the users table already exists so when you run your migrations it is trying to create a table that is already created in your database.

Note: Don't forget to backup your database first

Delete users table from the database also delete users entries from migrations table.

After, execute the migrate Artisan command:php artisan migrate


Now another your Question is: How to add new columns in my existing table?

You have to create a table using this command:

php artisan make:migration create_users_table

The output you got it like this: Created Migration: 2019_04_12_070152_create_users_table

Your Migration structure is something this:

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

Now you want to add new columns in your existing users table

php artisan make:migration add_phone_number_to_users_table --table=users

use the Schema::table() method (as you're accessing an existing table, not creating a new one). And you can add a column like this:

public function up()
{
     Schema::table('users', function (Blueprint $table) {
         $table->string('phonenumber')->after('name'); // use this for field after specific column.
     });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('users', function (Blueprint $table) {
        $table->dropColumn('phonenumber');
    });
}

After, you can run your migrations: php artisan migrate

Your new columns(phonenumber) are now added to your existing users table, which you can view in your database.

If you have still any doubt, see this video

Thursday, December 1, 2022
 
goatcat
 
4

Here you go,

Body bod = doc.MainDocumentPart.Document.Body;
foreach (Table t in bod.Descendants<Table>())
{
    t.Append(new TableRow(new TableCell(new Paragraph(new Run(new Text("test"))))));
}

Use LINQ to get the proper table.

EDIT:

Say you want to get the table that has 4 columns.

Body bod = doc.MainDocumentPart.Document.Body;
foreach (Table t in bod.Descendants<Table>().Where(tbl => tbl.GetFirstChild<TableRow>().Descendants<TableCell>().Count() == 4))
{
    t.Append(new TableRow(new TableCell(new Paragraph(new Run(new Text("test"))))));
}

Say you want to get the table that contains the word "mytable".

Body bod = doc.MainDocumentPart.Document.Body;
foreach (Table t in bod.Descendants<Table>().Where(tbl => tbl.InnerText.Contains("myTable")))
{
    t.Append(new TableRow(new TableCell(new Paragraph(new Run(new Text("test"))))));
}
Wednesday, August 17, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :