Retrieve current product, category and CMS page in Magento

Here are the quick snippet scripts for pulling out the current product, category and cms page from inside script or template files in Magento.

Get Current category

$_category = Mage::registry(‘current_category’);

Get Current Product

$_product = Mage::registry(‘current_product’);

Get Gurrent CMS Page

$_cmspage = Mage::registry(‘cms_page’)

How to get url of a category or product in magento .phtml file

For category url by category ID:

1
 <?php echo Mage::getModel("catalog/category")->load(5)->getUrl() ?>

To load products of a specific category:

1
2
3
4
5
 <?php                      
$cat_id = 8; // set desired category id$category = Mage::getModel('catalog/category')->load($cat_id);$products = $category->getProductCollection()->addCategoryFilter($category)->addAttributeToSelect('*');?>
<?php foreach ( $products as $_product ): ?>
    <a href="<?php echo $_product->getProductUrl() ?>"><img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(135, 135); ?>" width="135" height="135" title="<?php echo $_product->getName() ?>" alt="<?php echo $_product->getName() ?>" /></a>
<?php endforeach; ?>

Laravel Building HTML

Building HTML

Content

Entities

When displaying user input in your Views, it is important to convert all characters which have significance in HTML to their “entity” representation.
For example, the < symbol should be converted to its entity representation. Converting HTML characters to their entity representation helps protect your application from cross-site scripting: Converting a string to its entity representation:

1. echo HTML::entities(‘‘);

Using the “e” global helper:

1. echo e(‘‘);

Scripts And Style Sheets

Generating a reference to a JavaScript file:

echo HTML::script(‘js/scrollTo.js’);

Generating a reference to a CSS file:

echo HTML::style(‘css/common.css’);

Generating a reference to a CSS file using a given media type:

echo HTML::style(‘css/common.css’, array(‘media’ => ‘print’));

Further Reading:

Links

Generating a link from a URI:

1. echo HTML::link(‘user/profile’, ‘User Profile’);

Generating a link that should use HTTPS:

1. echo HTML::link_to_secure(‘user/profile’, ‘User Profile’);

Generating a link and specifying extra HTML attributes:

1. echo HTML::link(‘user/profile’, ‘User Profile’, array(‘id’ => ‘profile_link’));

Links To Named Routes

Generating a link to a named route:

echo HTML::link_to_route(‘profile’);

Generating a link to a named route with wildcard values:

$url = HTML::link_to_route(‘profile’, ‘User Profile’, array($username));

Further Reading:

  • Named Routes

Links To Controller Actions

Generating a link to a controller action:

1. echo HTML::link_to_action(‘home@index’);

Generating a link to a controller action with wildcard values:

1. echo HTML::link_to_action(‘user@profile’, ‘User Profile’, array($username));

Links To A Different Language

Generating a link to the same page in another language:

1. echo HTML::link_to_language(‘fr’);

Generating a link to your home page another language

1. echo HTML::link_to_language(‘fr’, true);

Mail-To Links

The “mailto” method on the HTML class obfuscates the given e-mail address so it is not sniffed by bots.
Creating a mail-to link:

1. echo HTML::mailto(‘example@gmail.com’, ‘E-Mail Me!’);

Creating a mail-to link using the e-mail address as the link text:

1. echo HTML::mailto(‘example@gmail.com’);

Images

Generating an HTML image tag:

1. echo HTML::image(‘img/smile.jpg’, $alt_text);

Generating an HTML image tag with extra HTML attributes:

1. echo HTML::image(‘img/smile.jpg’, $alt_text, array(‘id’ => ‘smile’));

Lists

Creating lists from an array of items:

1. echo HTML::ol(array(‘Get Peanut Butter’, ‘Get Chocolate’, ‘Feast’));

2. echo HTML::ul(array(‘Ubuntu’, ‘Snow Leopard’, ‘Windows’));

3. echo HTML::dl(array(‘Ubuntu’ => ‘An operating system by Canonical’, ‘Windows’ => ‘An operating system by Microsoft’));

Custom Macros

It’s easy to define your own custom HTML class helpers called “macros”. Here’s how it works. First, simply register the macro with a given name and a Closure:
Registering a HTML macro:

1. HTML::macro(‘my_element’, function()

2. {

3. return ‘

‘;

4. });

Now you can call your macro using its name:
Calling a custom HTML macro:

1. echo HTML::my_element();

Solving reindex issues with Product Flat Data in Magento

Check your exception.log file And find :

Product Flat Data index process unknown error:
exception ‘PDOException’ with message ‘SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`DATABASE_NAME`., CONSTRAINT `FK_CAT_PRD_FLAT_2_ENTT_ID_CAT_PRD_ENTT_ENTT_ID` FOREIGN KEY (`entity_id`) REFERENCES `catalog_product_entity` ()’ in /app/magento_oneline/lib/Zend/Db/Statement/Pdo.php:228
Stack trace:
#0 /app/magento_oneline/lib/Zend/Db/Statement/Pdo.php(228): PDOStatement->execute(Array)
#1 /app/magento_oneline/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
#2 /app/magento_oneline/lib/Zend/Db/Statement.php(300): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
#3 /app/magento_oneline/lib/Zend/Db/Adapter/Abstract.php(479): Zend_Db_Statement->execute(Array)

That error for

1 The key is here:
2 ?
3 1FK_CAT_PRD_FLAT_2_ENTT_ID_CAT_PRD_ENTT_ENTT_ID
4 That is telling you which table is failing. This exception tells that
5 the referential integrity between:
6 catalog_product_flat_2.entity_id and catalog_product_entity.entity_id is corrupted. This usually means some record(s)
7 contain(s) null in the field catalog_product_entity.entity_id, where they are expected to contain existing entity_ids.

Fixing this

In order to fix this issue, you need to find what the corrupted entries are. This is easy. In this case, you’ll need to create a query to get the empty registers:
?
1

SELECT a.entity_id FROM catalog_product_flat_2 AS a LEFT JOIN catalog_product_entity AS b ON a.entity_id = b.entity_id WHERE ISNULL(b.entity_id);
This will display the corrupted entities. You only need to delete them and that’s all.
?

1 +———–+
2 | entity_id |
3 +———–+
4 | 35427 |
5 | 35428 |
6 +———–+
7 2 rows in set (0.04 sec)
As example:
?
1DELETE FROM catalog_product_flat_2 where entity_id = ‘35427’;

Export and import MySQL databases through command line

command line

This method works for all database sizes, including very large ones.

You must be able to log into your server with SSH.

Export

1. Log into your server via SSH.
2. Use the command cd to navigate to a directory where your user has write access. Example:
cd /var/www/vhosts/example.com/httpdocs
3. Export the database by executing the following command:

mysqldump –add-drop-table -u admin -p`cat /etc/psa/.psa.shadow` dbname > dbname.sql

Once you execute this command, you will be prompted for your database password. Type in the password and hit enter. Your database will now start exporting. When it is done, you will see the command prompt again. If it is a large database, this may take a few minutes.
NOTE:
The following variables need to be replaced with your own information:

  • -u admin specifies the database username.
  • Username is “admin” and the password is a hashed version of your Plesk admin password.
  • dbname is the name of the database you are trying to export.
  • dbname.sql is the name you want to give your backup file, and can be whatever you want.
  • Omit the –add-drop-table argument if you plan to merge this backup with an existing database when you import it. This option means the backup will totally replace the old database when it is imported.

4. You can now download the resulting SQL file. Connect to your server with FTP, navigate to the directory where you created the dump file, and download it.
5. Remove the SQL file from your web-accessible directory, if you created it in a public folder. Otherwise, anyone can download it from the web.

Import

1. Use FTP to upload your SQL file to your server. You can upload it to your default FTP directory. See Step 1 in the “Export” instructions above for another suggestion. Alternately, you can use scp to upload your file via SSH.
2. Log into your server via SSH.
3. Use the command cd to navigate into the directory where you uploaded your backup file in Step 1. If you uploaded the backup into your public htttpdocs directory, go here:

1
cd /var/www/vhosts/example.com/httpdocs/

4. Import the database by executing the following command:

1
mysql -u admin -p`cat /etc/psa/.psa.shadow` dbname &lt; dbname.sql

OR:

1
mysql -u admin -p`cat /etc/psa/.psa.shadow` dbname -e 'source dbname.sql'

Once you execute this command, you will be prompted for your database password. Type it in and hit enter. Your database will now import. It may take a few minutes if you have a large database. When the import is done, you will be returned to the command prompt.

NOTE:

  • Variables are the same as in Step 3 from the Export section above. Please check Step 3 in the “Export” section to make sure you are correctly replacing the example code with your own information.
  • dbname.sql is the actual name of your SQL file.
  • If you have a gzipped backup of your database, you can use this line instead:gunzip < dbname.gz | mysql -u admin -p`cat /etc/psa/.psa.shadow` dbname

    You can enter in your own username, database name, and backup file name, as before. dbname.gz is the name of your gzipped backup file. Use “unzip” instead of “gunzip” for zipped files.

5. Remove the SQL file from your web-accessible directory, if you uploaded it to a public folder. Otherwise, anyone can download it from the web.

If you get an error that looks like this:

Got Error: 1045: Access denied for user ‘admin@example.com’ (using password: YES) when trying to connect

You have entered an incorrect password. Please retype it carefully, or reset your password in the AccountCenter. See How can I change my Plesk admin password? for instructions.
If you get an SQL error during the import, you can force it to finish by adding “-f” to the command, which stands for “force.” For example:

1
mysql -f -u admin -p`cat /etc/psa/.psa.shadow` dbname &lt; dbname.sql

This can help you finish an import if you have a few corrupt tables, but need to get the database as a whole imported before you do anything else.

Embed Images from Google Maps In Emails & Blogs Without Using Screen Capture Software


It is now possible to embed live images of Google Maps in emails and other websites (like MySpace, Facebook or WordPress.com) that do not allow JavaScript.

Earlier you had to take a screenshot of the Google Maps and save that as an image file but that’s no longer necessary as this Static Maps Wizard will let you create a still but dynamic image of any location on Google Maps.
For instance, the map of Hyderabad above is not a screenshot but a live image served from Google Maps using this URL.

You can place the Google Maps image in any web page using the standard tag. For embedding maps in web emails (like Gmail), simply compose a new message and drag the Google Map on to the email body. Thanks Tom Manshreck.

Host your Podcasts on Google Drive for Free

If you are looking to publish your own audio or video podcasts, you’ll need space on a public web server to host the MP3 or MP4 files of your podcast. When a user subscribes to your podcast feed in iTunes, or another podcatcher app, the podcast files will be downloaded from this server to the user’s computer (or mobile phone).

Where do you host the podcast files? If you have signed up for a web hosting account, you can use the rented space to host the podcast files else you may consider using Google Drive – it is free, you can host both audio and video podcast files and there are no known bandwidth restrictions.

Free Podcast Hosting on Google Drive

Here’s how you can use your Google Drive to host your podcast in two minutes.
We will first create a Podcast folder in Google Drive to store the podcast files and then make this folder public so anyone can download the episodes stored in this Google Drive folder. Any video file that you upload to this folder in Drive will have a public URL that you can use in your Podcast XML feed.

Click here and authorize the script to access to your Google Drive. The script will create a new public folder in your Google Drive for hosting the files.
Go to
drive.google.com in your desktop browser and upload one or more podcast files in the new Podcasts folder that you created in Step #1.
Once the files have been uploaded, open that folder link in your browser (
see example) and you should see a list of all the uploaded podcast files.
Right-click any podcast file (see the above screenshot) to copy the file’s URL which you can then paste in your podcast RSS feed –
see example).

The podcasts will be served from googledrive.com.

Other than the actual podcast episodes, you may also upload art work, logos and other image files that may be required for submitting your Podcast into the iTunes store.

A Simple Way to Protect Images from ‘Casual Copying’

If you don’t want other people to download images from your website, don’t put them online because – the way the web works – it is almost impossible to prevent someone from copying or saving your images.

However there’s one little trick that may discourage the less-technical people from casually copying, or even hot-linking, to your web images. To give you an example, try saving the following image to your computer using the standard “save as” option.

The “save picture” option under right-click is still available for the above image but instead of downloading the actual photograph, all it would save is a blank image. Also, the URL for the image (under Properties) would appear as some junk characters (it’s called a data URI) and thus would deter the non-techies from hotlinking to that image.
Here’s how you may implement something similar for your own images:
The standard embed code for an image looks something like this:

1
<img src="photograph.jpg" alt="" width="500" height="250" />

What you need to do is change the value of the src attribute to point to a blank image and then add a new style attribute to render the actual image. Also make sure that the value of the height and the width parameters are exactly the same as the actual image.

1
<img style="background-image: url('photograph.jpg');" src="data:image/gif;base64, R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" alt="" width="500" height="250" />

This is like overlaying a completely transparent screen over your photograph and anyone trying to save the image will end up downloading that screen instead of the image.

Obviously, there are simple workarounds to get around the above method. For instance, a copy of the full image will still be available in your browser’s cache. You may look at the HTML source or may even save the image using screen capture but again, these techniques may not always be known to the non-technical users of your website.

How to change magento admin password through phpmyadmin ?

It seems like the password must be typed and not copy/paste at least on the install part. good to know ;o)

The default login is : admin The default password is : 123123
If you are having troubles and want to reset it to a different password, just run at your sql database:

1
SELECT * FROM admin_user;

Then, find the username you want to modify in the listing provided – ‘admin’ in this example. Then, to update the password, type:

1
 UPDATE admin_user SET password=CONCAT(MD5('qXpassword'), ':qX') WHERE username='admin';

‘qX’ would be changed to whatever you want it to be and same goes for ‘password’
You can also do this in phpMyAdmin, find the admin_user field and choose MD5 when updating password.
If you want to add a new admin user, you must not only create a new entry in the table ‘admin_user’, but you also have to insert an entry in the table ‘admin_role’ which has to be associated with the user by the field ‘user_id’.

Create an Admin Interface in Laravel

Nowadays, you’d be hard-pressed to find a PHP developer who doesn’t know about Laravel. If you are one of these people, visit the Laravel site ASAP! The framework is insanely popular in the PHP community these days because of the thought that has gone into it to make it easy to use and robust as hell! We will demonstrate its easy-of-use by building an admin interface that we can use to manage our users in some fake application we have already built. Let’s do it!

The Files

We need to download the files locally and get our project configs set up. Let’s do this really quick. Run the following command to download the files and all its dependencies. I’m assuming you have composer downloaded globally on your machine.
1composer create-project laravel/laravel useradmin
This will create a directory called useradmin, put all of Laravel’s files in it, and then download all of Laravel’s dependencies. Next, we need to fill in our configs. Go into the config files and fill in what’s necessary. I always fill in URL and timezone in app.php and the MySQL info in database.php.
EDIT: Thanks to Triggvy Gunderson for pointing out the following two extra steps to take. You should change the debug option to true when in development to make sure you can see a helpful error screen. Also, make sure to make the app/storage directory writable by executing the following from the root of your project:
1chmod -R 777 app/storage
Now that all that initial setup is done, let’s create and seed our database.

The Database

We need to create our database table to hold our users in, and then we will seed it with some data for us to play with. Run the following command to get some boilerplate code written for us to make our table.
1php artisan migrate:make create_users_table –create=users
If you go to /app/database/migrations, there will be a new migration file waiting for you. Let’s fill it out.

1
2
3
4
5
6
7
8
<!--?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function(Blueprint $table) { $table-&gt;increments('id');&lt;br ?--> $table-&gt;string('username');
$table-&gt;string('email');
$table-&gt;string('password');
$table-&gt;string('first_name');
$table-&gt;string('last_name');
$table-&gt;timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop(‘users’);
}

}

This is all we need to create our database table! Piece of cake. Now let’s seed the table to give us some fake data to play with later.

1
 

‘username’ => ‘doctorv’,
’email’ => ‘darthv@deathstar.com’,
‘password’ => Hash::make(‘thedarkside’),
‘first_name’ => ‘Darth’,
‘last_name’ => ‘Vader’,
‘created_at’ => new DateTime(),
‘updated_at’ => new DateTime()
]);

DB::table(‘users’)->insert([
‘username’ => ‘goodsidesoldier’,
’email’ => ‘lightwalker@rebels.com’,
‘password’ => Hash::make(‘hesnotmydad’),
‘first_name’ => ‘Luke’,
‘last_name’ => ‘Skywalker’,
‘created_at’ => new DateTime(),
‘updated_at’ => new DateTime()
]);

DB::table(‘users’)->insert([
‘username’ => ‘greendemon’,
’email’ => ‘dancingsmallman@rebels.com’,
‘password’ => Hash::make(‘yodaIam’),
‘first_name’ => ‘Yoda’,
‘last_name’ => ‘Unknown’,
‘created_at’ => new DateTime(),
‘updated_at’ => new DateTime()
]);
}

}

Make sure to uncomment the line in DatabaseSeeder.php so that our seed file will actually be called. Lastly, run the following command to run the migrations and then seed the database.
1php artisan migrate –seed

The Login Page

Now, we should try to block off the admin area from people who shouldn’t be able to have access. Let’s add the logic for this into our application. Make your routes.php look like the below:

1
2
1 <!--?php &lt;br ?--> 2
3 Route::controller('/', 'HomeController');

That line creates a “controller” route in our application. This means we can create a route by editing our controller, not our routes file. For example, in our HomeController, we could set up a route that is picked up when we send a PUT request to the url /example by making a method called putExample. Let’s get into it. Make your HomeController look like the following:

1
 

{
return Redirect::intended(‘/user’);
}

return Redirect::back()
->withInput()
->withErrors(‘That username/password combo does not exist.’);
}

public function getLogin()
{
return Redirect::to(‘/’);
}

public function getLogout()
{
Auth::logout();

return Redirect::to(‘/’);
}

}

Here we are setting up the login routes to display the login form and process it. The getIndex route simply returns a view to display, which we will make in a moment. We then set up a route to handle the input we receive from the login form. It uses the Auth::attempt to login the user. This method is another example of Laravel making our job easier! It tests the given credentials against credentials in the database. The table to use is stated in the auth.php config file. It will automatically log the user in and return true if the user credentials check out. If not, we are redirecting back to the previous page (our login page) with the given input and with an error message to let the user know what’s up. We also create a login route that redirects back to our home page. Lastly, we create a logout route that will log a user out using Laravel’s Auth::logout function and then redirect to our home page.
Now that we have the routes created, let’s create the views. We only need one view for this controller. We need to put it in the app/views/home/ directory. We will call it index.blade.php. Laravel uses the blade template engine, which allows us to keep our views readable but powerful. Put the following code in app/views/home/index.blade.php.

1
@extends('layouts.master')

@section(‘title’) Login @stop

@section(‘content’)

@if ($errors->has())
@foreach ($errors->all() as $error)

{{ $error }}

@endforeach
@endif

Login

{{ Form::open([‘role’ => ‘form’]) }}

{{ Form::label(‘username’, ‘Username’) }}
{{ Form::text(‘username’, null, [‘placeholder’ => ‘Username’, ‘class’ => ‘form-control’]) }}
{{ Form::label(‘password’, ‘Password’) }}
{{ Form::password(‘password’, [‘placeholder’ => ‘Password’, ‘class’ => ‘form-control’]) }}
{{ Form::submit(‘Login’, [‘class’ => ‘btn btn-primary’]) }}

{{ Form::close() }}

@stop

Nothing crazy happening here. We are creating a form that will submit to our route. By default, Laravel forms submit a POST request to the same URL we are on. This is perfect for the way we set up our login routes. At the top, you can see we are extending a layout. Let’s create that too. This is a good practice for making extendable routes in your applications. Use the layouts to create basic templates for your views so your main view files need the least amount of code in them. Layouts usually include the CSS and JavaScript files that are used in all views. Below is the layout I used. It should be in app/views/layouts/master.blade.php.

1
 

@yield(‘title’) | User Admin

 

 

@yield(‘content’)

 
This is a basic layout. It brings in Twitter Bootstrap and Font Awesome just to make our views look pretty. I’m not much of a designer. Bootstrap is my savior!
In your browser, navigate to your project. I set up a virtual host for mine. So, I go to http://local.useradmin.com. This loads up the login screen we created. Going great so far. Let’s test that we get an error if we don’t enter valid credentials. Enter anything crazy in the username and password fields and hit enter. You should be taken back to the same page with an error at the top and the username already filled in. Awesome-sauce. Now let’s make sure we can get logged in. Log in with one of the credentials we seeded our database with. I like the Darth Vader one, personally. Hit enter and…wait. What the hell? What’s this error? Well, we haven’t created that route yet. Laravel is kind enough to let us know what we did wrong. So let’s make that now!

The User Management

Now, we need to make the user management functionality. First, let’s add a convenience method to our User model that we will user in our admin view. Add the following method to your User model.

1
2
3
4
5
6
7
8
9
1 /**
2 * Get the user's full name by concatenating the first and last names
3 *
4 * @return string
5 */
6 public function getFullName()
7 {
8 return $this-&gt;first_name . ' ' . $this-&gt;last_name;
9 }

This is a method to return a user’s full name. This is just a convenience. I use this in all my projects. Now that we have this, let’s add a route to our routes file to expose our the user controller we will create to our application. Make your routes.php file look like the below.

1
2
3
1 <!--?php &lt;br ?--> 2
3 Route::resource('/user', 'UserController');
4 Route::controller('/', 'HomeController');

We added a resource route. This allows us to interact with our controller in a RESTful way. If you don’t know REST, then read up here! It just standardizes the way we interact with our application. Now, let’s create our controller. Let’s utilize Laravel’s command line utility Artisan and have it create some boilerplate code for us. Run the following command.
1php artisan controller:make UserController –except=show
This creates a RESTful controller for us. It can be found in app/controllers. It has all the methods in it we will use. Notice I passed the except option with a value of show. This tells Artisan that we want all the methods in our code except the show method. For our particular use, we don’t need a page just one user. For a better explanation of each of these methods, see the Laravel docs.
Let’s populate our controller with our functionality. Make it look like the below code.

1
 

}

/**
* Display a listing of the user.
*
* @return Response
*/
public function index()
{
$users = User::all();

return View::make(‘user.index’, [‘users’ => $users]);
}

/**
* Show the form for creating a new user.
*
* @return Response
*/
public function create()
{
return View::make(‘user.create’);
}

/**
* Store a newly created user in storage.
*
* @return Response
*/
public function store()
{
$user = new User;

$user->first_name = Input::get(‘first_name’);
$user->last_name = Input::get(‘last_name’);
$user->username = Input::get(‘username’);
$user->email = Input::get(’email’);
$user->password = Hash::make(Input::get(‘password’));

$user->save();

return Redirect::to(‘/user’);
}

/**
* Show the form for editing the specified user.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
$user = User::find($id);

return View::make(‘user.edit’, [ ‘user’ => $user ]);
}

/**
* Update the specified user in storage.
*
* @param int $id
* @return Response
*/
public function update($id)
{
$user = User::find($id);

$user->first_name = Input::get(‘first_name’);
$user->last_name = Input::get(‘last_name’);
$user->username = Input::get(‘username’);
$user->email = Input::get(’email’);
$user->password = Hash::make(Input::get(‘password’));

$user->save();

return Redirect::to(‘/user’);
}

/**
* Remove the specified user from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id)
{
User::destroy($id);

return Redirect::to(‘/user’);
}

}
That’s alot. I’ll walk through this kind of quickly for the sake of brevity. At the top, I create a construct method for our controller. This will be fired each time or controller is created. I used the beforeFilter method in it. This will fire the given filter whenever this controller is created. For this particular case, I only want to make sure the user is logged in. This filter is supplied to us by Laravel out of the box. If a user is not logged in, it will send them to the /login page. This is why we created the login route in our HomeController that redirects to our homepage. Otherwise we would get an error.
In the index, we get all our users and pass them to our main view. The create method displays the form to add a new user. The store method grabs the input given in the request and saves the user to the database. The edit method grabs the user specified in the URL and sends that user to the view to be edited. The update method grabs the user and updates its attributes. Then saves the changes and redirects back to the main user screen. Lastly, the destroy method destroys the user specified in the URL and then redirects to the main user screen.
The only thing left is to make our views. Let’s do it. The first one should be our main index page. Let’s put it in app/views/user/index.blade.php.

1
 

@extends(‘layouts.master’)

@section(‘title’) Users @stop

@section(‘content’)

User Administration Logout

@foreach ($users as $user)@endforeach

Name Username Email Date/Time Added
{{ $user->getFullName() }} {{ $user->username }} {{ $user->email }} {{ $user->created_at->format(‘F d, Y h:ia’) }} Edit
{{ Form::open([‘url’ => ‘/user/’ . $user->id, ‘method’ => ‘DELETE’]) }}
{{ Form::submit(‘Delete’, [‘class’ => ‘btn btn-danger’])}}
{{ Form::close() }}

Add User

@stop
Again, we are extending our master layout. We are creating a table and using a foreach loop to iterate over each user that was passed into the view from the controller. We are outputting each of the attributes we keep in the database minus the password. We are also outputting two buttons – one to edit the user and one to delete them. Notice the edit button is just a link but the delete button is actually a form. This is because we need to send a delete request to our controller. This will ensure the destroy method is called. Because browsers don’t support the PUT or DELETE methods of forms, Laravel adds a hidden attribute to the form that lets the application know we are wanting to use the DELETE method. Also, notice we are using our helper method to output the user’s full name. We output a button after the table to add a new user. Lastly, we put a table at the top to logout. Alot of functionality for such a small file, huh?
Now, let’s build our new user form. This is simple.

1
 

@extends(‘layouts.master’)

@section(‘title’) Create User @stop

@section(‘content’)

@if ($errors->has())
@foreach ($errors->all() as $error)

{{ $error }}

@endforeach
@endif

Add User

{{ Form::open([‘role’ => ‘form’, ‘url’ => ‘/user’]) }}

{{ Form::label(‘first_name’, ‘First Name’) }}
{{ Form::text(‘first_name’, null, [‘placeholder’ => ‘First Name’, ‘class’ => ‘form-control’]) }}
{{ Form::label(‘last_name’, ‘Last Name’) }}
{{ Form::text(‘last_name’, null, [‘placeholder’ => ‘Last Name’, ‘class’ => ‘form-control’]) }}
{{ Form::label(‘username’, ‘Username’) }}
{{ Form::text(‘username’, null, [‘placeholder’ => ‘Username’, ‘class’ => ‘form-control’]) }}
{{ Form::label(’email’, ‘Email’) }}
{{ Form::email(’email’, null, [‘placeholder’ => ‘Email’, ‘class’ => ‘form-control’]) }}
{{ Form::label(‘password’, ‘Password’) }}
{{ Form::password(‘password’, [‘placeholder’ => ‘Password’, ‘class’ => ‘form-control’]) }}
{{ Form::label(‘password_confirmation’, ‘Confirm Password’) }}
{{ Form::password(‘password_confirmation’, [‘placeholder’ => ‘Confirm Password’, ‘class’ => ‘form-control’]) }}
{{ Form::submit(‘Login’, [‘class’ => ‘btn btn-primary’]) }}

{{ Form::close() }}

@stop
The code in this file should look very familiar. It looks just like our login form except there are more fields in it. Also, we had to overwrite the URL our form submits to. To stick with the RESTful interface, we need to submit a POST request to /user.
Lastly, let’s make the form to edit a user.

1
 

@extends(‘layouts.master’)

@section(‘title’) Create User @stop

@section(‘content’)

@if ($errors->has())
@foreach ($errors->all() as $error)

{{ $error }}

@endforeach
@endif

Edit User

{{ Form::model($user, [‘role’ => ‘form’, ‘url’ => ‘/user/’ . $user->id, ‘method’ => ‘PUT’]) }}

{{ Form::label(‘first_name’, ‘First Name’) }}
{{ Form::text(‘first_name’, null, [‘placeholder’ => ‘First Name’, ‘class’ => ‘form-control’]) }}
{{ Form::label(‘last_name’, ‘Last Name’) }}
{{ Form::text(‘last_name’, null, [‘placeholder’ => ‘Last Name’, ‘class’ => ‘form-control’]) }}
{{ Form::label(‘username’, ‘Username’) }}
{{ Form::text(‘username’, null, [‘placeholder’ => ‘Username’, ‘class’ => ‘form-control’]) }}
{{ Form::label(’email’, ‘Email’) }}
{{ Form::email(’email’, null, [‘placeholder’ => ‘Email’, ‘class’ => ‘form-control’]) }}
{{ Form::label(‘password’, ‘Password’) }}
{{ Form::password(‘password’, [‘placeholder’ => ‘Password’, ‘class’ => ‘form-control’]) }}
{{ Form::label(‘password_confirmation’, ‘Confirm Password’) }}
{{ Form::password(‘password_confirmation’, [‘placeholder’ => ‘Confirm Password’, ‘class’ => ‘form-control’]) }}
{{ Form::submit(‘Login’, [‘class’ => ‘btn btn-primary’]) }}

{{ Form::close() }}

@stop

This form is almost exactly the same as the add user form. On this form, we have to overwrite the URL is submits to and also the method it uses. We want this one to submit a PUT request. We also use the model form method instead of the open method. This method does the same thing as the open method except we supply it with a user and it fills in the fields for us by default. This is perfect for an edit form. Thanks Laravel!

Wrapping Up

As you can see, Laravel makes doing common tasks super easy! One thing we should add to this is roles and permissions. We need a way to keep unauthroized users from access our user admin page. Right now, any signed-up user can access it. That isn’t very secure. To add roles and permissions to your project, see my other posts, Adding Roles to Laravel Users and Using Entrust to Add Roles and Permissions to Laravel 4, and check out my Laravel package Drawbridge. If this has wet your appetite for Laravel, check out the docs. It’s a great system to understand since it is the most popular right now. Leave a comment if you liked the article or just want to say, “Hi!”

Further Reading