• 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 Reply Cancel reply

0 Comments
Inline Feedbacks
View all comments

Primary Sidebar

Popular

  • Testing Event Listeners In Jest (Without Using A Library)
  • How To Get The Hash of A File In Node.js
  • How To Mock uuid In Jest
  • Which Neural DSP Archetype Plugins Should You Buy?
  • How to Copy Files Using the Copy Webpack Plugin (without copying the entire folder structure)
  • Removing A Character From The Start/End of a String In Javascript
  • How To Convert FormData To JSON Object
  • How To Correctly Use Semantic HTML5 <article>, <main> and <section> Tags
  • Wild Natural Deodorant Review
  • How to Use Neural DSP Archetype Plugins With the Quad Cortex

Recent Comments

  • Thebe on How to Remove the My Sites Menu From the WordPress Admin Bar
  • Maccas worker jn the 2000s on Dear McDonald’s: bring back the Warm Cookie Sundae, you cowards
  • Anamika Singh on Testing Event Listeners In Jest (Without Using A Library)
  • Stefan on A List of WordPress Gutenberg Core Blocks
  • pandammonium on A List of WordPress Gutenberg Core Blocks

Copyright © 2022 · Dwayne Charrington · Log in

wpDiscuz