• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

I Like Kill Nerds

The blog of Australian Front End / Aurelia Javascript Developer & brewing aficionado Dwayne Charrington // Aurelia.io Core Team member.

  • Home
  • Aurelia 2
  • Aurelia 1
  • About
  • Aurelia 2 Consulting/Freelance Work

Mass Assignment in Laravel 4

General · August 4, 2014

A wonderful feature of Ruby on Rails and also coincidentally in Laravel 4 is mass assignment. Basically you can throw an array of values at your model and insert or update an entry from a form.

In Laravel 3 you had a method called fill which was called on your model object like this: $user = new User; $user->fill($array_values); – in Laravel 4 the method has been replaced with create instead.

The below example will touch upon validation based on rules defined in your model and is based on a fictitious blog application.

Mass Assignment model example

The Controller

			<?php

		class PostController extends \BaseController {

			// Handles our POST request for storing a user
			public function store()
			{
				$validator = Validator::make(Input::all(), Post::$rules);

				if ( $validator->passes() )
				{
					$post = new Post;
					$post::create(Input::all());
					$post->save();

					return Redirect::to('post/'.$post->id);
				}
				else
				{
					View::make('public.post.add');
				}
			}

		}
	

The Model

			<?php

		class Post extends Eloquent {
			
			protected $table = 'posts';

			protected $guarded = array('id');

			public static $rules = array(
				'name' => 'required|min:5',
				'description' => 'required',
			);

		}
	

In a nutshell that is mass assignment using the create method of the Model object instance. We don’t go into depth regarding validation and controllers as it is assumed you already are aware how those work.

Dwayne

Leave a ReplyCancel reply

0 Comments
Inline Feedbacks
View all comments

Primary Sidebar

Popular

  • Handling Errors with the Fetch API
  • How To Get The Hash of A File In Node.js
  • How To Paginate An Array In Javascript
  • Thoughts on the Flipper Zero
  • Testing Event Listeners In Jest (Without Using A Library)

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz