Mass Assignment Exception Laravel 4 Tutorials

If you would like to know more about Laravel, watch our Laravel live lesson with Isaac Castillo, teacher of our recent Laravel course.

In the previous part, we’ve bootstrapped our Laravel CRUD application by creating the database, some controllers, basic routes and simple views. In this part, we’ll wrap things up and implement proper CRUD.

If you’d like to follow along through this interactive walk through Laravel’s docs, please catch up by reading the first part now.

Creating A Record

Continuing right where we left off, let’s create the page where we’ll actually perform this action. In our , let’s return a view like this:

And now, in our views directory, let’s create , and enter some starter content:

At this point, we could manually create a form, but Laravel offers a package to lighten this load for us – Illuminate/Html. Let’s pull that in quickly by running the following command:

Now, inside our file, let’s add the service provider to the list:

Let’s add the aliases:

We can now easily create a form in our file. Let’s go ahead and do that using the form facade and blade syntax:

Check out this screenshot of our view so far.

One important thing to note here is that I’ve specified the route on which we will POST to, according to our resourceful routes list. We’ll use the store method to process the data, so let’s head back to our , and start processing that data.

Let’s turn our heads to requests in Laravel.

The Request facade will grant you access to the current request that is bound in the container.

We can obtain our request instance in two ways, according to the documentation. Let’s stick with the dependency injection method. Our method should now look like this:

Now, we can dump out the information to see what gets posted. We’ll use the helper function, , which is included by default in Laravel. It combines Symphony’s VarDupmer component, and the PHP function. Add the following to the method:

Now submit the empty form, and you’ll see the data. Go back and fill in some dummy data in the form, and you’ll see the request updated. If we’re not interested in any validation, then saving the new task to the database is easy. In the docs for Eloquent, we’ll notice that we can call the method to create a new row in our table. Let’s do that by adding the following to our method. We’ll also redirect back to where we came from:

We’re ready to create a new task now. Let’s go ahead and enter some dummy data and submit it. Uh oh… there’s a . Laravel by default prevents mass assignment, which is a good thing. This just means that we have to declare which fields are mass-assignable. I suggest you read up on this, but here’s what our updated model will look like:

Now, let’s try to add our task again. If we were successful, we should be redirected back to where we came from, i.e. the “create task” page. There’s no indication right now as to whether the task was successfully added, but let’s check the database through the command line:

We should see the table returned with our new entry. Sweet! What about success messages and validation? Let’s first validate our input, to make sure all fields are required. Laravel ships with a really easy-to-use Validator class, and a quick read should have us going in no time. We’re validating in our controller, so let’s look at that section. Let’s validate our input by adding this to the beginning of the method:

Notice now that if we leave out any of our input, the rest of our method doesn’t execute, and we remain on the page with whatever input has already been entered. Laravel will automatically throw an error, which we can access in our blade template. Let’s insert the following snippet above our form:

Now, we’ll see the errors neatly written out for us.

What about a success message? Well, if our validator passes, the rest of our code will execute, and we can redirect back with a Session flash message. Update the method to create a new flash message:

Now, we can add this to our blade template:

Here’s what we should see.

We’re now validating and adding tasks, as well as passing data back to the view for output. Excellent. We still need a way to actually see our records.

Reading Records

Back in our method, we can now output all tasks that we’ve created so far. Add this to the method:

We can access and output the tasks like this:

Here’s a screenshot for the index view.

Let us now figure out how we’re going to display a single record. In this current app, it’s probably not necessary because we’re already outputting all the information, but we’ll do it anyway. If we look at our routes list, it’s apparent that the route is the way to go. It accepts a wildcard in the URL, and for our app, we’ll use the ID of the task. As before, we’ll create a file and extend our master layout:

Now, let’s update our method:

If we navigate to a URL with a random wildcard – – we should see our dummy template. Let’s actually fetch the correct task. Using Eloquent, we can search for a record with the matching ID, and if none are found, we’ll throw a which we can catch. If the record is found, we can access it in our view. Here’s the updated method:

Now in our view, we can output the record properly like this:

Navigate to , and you should see the output.

Back in our view, we can now output the links to each individual task:

Notice that we passed in the correct wildcard based on the task ID. You should now be able to click through nicely! Let’s move on to editing.

Updating A Record Using Form-Model Binding

By now, you probably realize how easy it is to get a new view ready for our RESTful app. It’s no different this time, so we’ll create the file, pull in the master layout, and link the corresponding controller method to it. Here’s the method:

And here’s the view to match:

If you look at the routes list, you’ll notice that the edit route also accepts a wildcard. We’ll be consistent and use the ID. Navigating to will display the dummy page, but let’s pull in the proper content. First of all, we can update all our “edit” links on the and views like this:

Notice again how we’re calling the correct route and passing in the corresponding wildcard. In our edit template, we’re going to want a similar form to the one we used to create a task, but it would be pretty useful if the form was already populated with the existing fields. Thanks to Laravel’s form-model binding, this is a piece of cake. We’ll copy over the create form, although a better practice would be to extract this to a partial of some sort. In any case, we’ll copy it over, and bind our model to it:

Notice how we’re using a PATCH request in the form to stay in line with our RESTful resource. Notice also how we are calling on the variable , binding it to the model, and referencing the ID which will be used to look up the table. This means that we have to pass in the correct task. In the , we can update the method to this:

Just like before, if an ID isn’t found, we’ll get the . We can, at this point, copy over our errors snippet again, but this isn’t very DRY at all. Don’t worry, we can fix that easily by leveraging partials. Blade allows us to reference any file by using the directive. First, let’s create a folder in our views directory called partials. In there, I’ll create a sub-directory called , and then a file called . Let’s copy over our errors snippet into this new file:

Now, we can reference it in any of our files like this:

We can now replace the original snippet in our template with this partial reference, and reference it in our edit template as well. The whole edit view should look like this now:

Here’s a screenshot of the view when we’re editing a task.

Let’s jump into our method now, which will receive the data from the form submission, and try to update our record. Like before, we’ll validate our input, and log the errors in our view if any exist. If validation passes, we’ll grab the input, update the task, save it, and redirect back with a success message. Here’s what the method looks like:

Try it out and see for yourself, it works! You can now create, read, and update records, but let’s cross the final hurdle.

Deleting A Record

Deleting a record RESTfully actually requires a DELETE request. You can get around this outside the controller with JavaScript, but that’s a bit beyond the scope of this article. If we view a single task, you’ll notice that I left a placeholder button there to delete it. We actually need to change this into a form that sends a DELETE request to the method, and handle the record deletion there. Here’s our updated show template incorporating the delete form:

Inside our , we can handle the request in the method, rounding off our RESTful controller. Once again, Eloquent makes this a breeze. We’ll fetch the associated record in the table, delete it, and redirect back to the task list:

At this point, let’s refactor our flash message into the master layout file so that it shows up on every template whenever a flash message is posted. We can remove it from the create and edit templates, and keep it only in the master layout like this:

Now, navigate to a task, and delete it. You’ll be redirected back to the task list with a flash message informing you that the task has successfully been deleted. Of course, your task list will be updated to match.

Wrapping Up

We’ve tapped into a lot of core concepts in this tutorial, and touched on a lot of neat Laravel functionality. By building up this CRUD application from scratch, we’ve gotten our taste buds wet with the Laravel workflow.

You should have a solid base and understanding to go on and build something yourself. I highly recommend checking out the various parts of the documentation to see what’s available, and just experimenting around as well. Use this as a building block, and get out there and show off your artisanal spirit. Feedback? Comments? Leave them below!

Continue learning about Laravel with our Laravel live lesson. One teacher, one lesson, followed by your Laravel questions.

I'm a web designer & developer from Trinidad & Tobago, with a degree in Mechanical Engineering. I love the logical side of the web, and I'm an artist/painter at heart. I endorse progressive web techniques, and try to learn something every day. I try to impart my knowledge as much as possible on my personal blog, I love food, I surf every weekend, and I have an amazing creative partnership with fellow mischief maker Elena. Together, we run SAYSM.


// Displays help for a given command php artisan --help OR -h // Do not output any message php artisan --quiet OR -q // Display this application version php artisan --version OR -V // Do not ask any interactive question php artisan --no-interaction OR -n // Force ANSI output php artisan --ansi // Disable ANSI output php artisan --no-ansi // The environment the command should run under php artisan --env // -v|vv|vvv Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug php artisan --verbose // Display the framework change list php artisan changes // Remove the compiled class file php artisan clear-compiled // Put the application into maintenance mode php artisan down // Regenerate framework autoload files php artisan dump-autoload // Display the current framework environment php artisan env // Displays help for a command php artisan help // Lists commands php artisan list // Optimize the framework for better performance php artisan optimize // List all registered routes php artisan routes // Serve the application on the PHP development server php artisan serve // Change the default port php artisan serve --port 8080 // Get it to work outside localhost php artisan serve --host // Interact with your application php artisan tinker // Bring the application out of maintenance mode php artisan up // Create a new package workbench php artisan workbench // Publish a package's assets to the public directory php artisan asset:publish [--bench[="vendor/package"]] [--path[="..."]] [package] // Create a migration for the password reminders table php artisan auth:reminders-table // Flush the application cache php artisan cache:clear // Create a new Artisan command (L3:task) php artisan command:make name [--command[="..."]] [--path[="..."]] [--namespace[="..."]] // Publish a package's configuration to the application php artisan config:publish // Create a new resourceful controller php artisan controller:make [--bench="vendor/package"] // Seed the database with records php artisan db:seed [--class[="..."]] [--database[="..."]] // Set the application key php artisan key:generate // Database migrations php artisan migrate [--bench="vendor/package"] [--database[="..."]] [--path[="..."]] [--package[="..."]] [--pretend] [--seed] // Create the migration repository php artisan migrate:install [--database[="..."]] // Create a new migration file php artisan migrate:make name [--bench="vendor/package"] [--create] [--package[="..."]] [--path[="..."]] [--table[="..."]] // Reset and re-run all migrations php artisan migrate:refresh [--database[="..."]] [--seed] // Rollback all database migrations php artisan migrate:reset [--database[="..."]] [--pretend] // Rollback the last database migration php artisan migrate:rollback [--database[="..."]] [--pretend] // Publish a package's migrations to migration directory php artisan migrate:publish vendor/package // Listen to a given queue php artisan queue:listen [--queue[="..."]] [--delay[="..."]] [--memory[="..."]] [--timeout[="..."]] [connection] // Subscribe a URL to an push queue php artisan queue:subscribe [--type[="..."]] queue url // Process the next job on a queue php artisan queue:work [--queue[="..."]] [--delay[="..."]] [--memory[="..."]] [--sleep] [connection] // Create a migration for the session database table php artisan session:table // Publish a package's views to the application php artisan view:publish [--path[="..."]] package php artisan tail [--path[="..."]] [--lines[="..."]] [connection]


composer create-project laravel/laravel folder_name composer install composer update composer dump-autoload [--optimize] composer self-update


Config::get('app.timezone'); //get with Default value Config::get('app.timezone', 'UTC'); //set Configuration Config::set('database.default', 'sqlite');


RESTful Controllers
Route::resource('posts','PostsController'); //Specify a subset of actions to handle on the route Route::resource('photo', 'PhotoController',['only' => ['index', 'show']]); Route::resource('photo', 'PhotoController',['except' => ['update', 'destroy']]);
Triggering Errors
App::abort(404); App::missing(function($exception){}); throw new NotFoundHttpException;
Route Parameters
Route::get('foo/{bar}', function($bar){}); Route::get('foo/{bar?}', function($bar = 'bar'){});
HTTP Verbs
Secure Routes
Route Constraints
Route::get('foo/{bar}', function($bar){}) ->where('bar', '[0-9]+'); Route::get('foo/{bar}/{baz}', function($bar, $baz){}) ->where(array('bar' => '[0-9]+', 'baz' => '[A-Za-z]')) // Set a pattern to be used across routes Route::pattern('bar', '[0-9]+')
Named Routes
Route Prefixing
Route Namespacing
Sub-Domain Routing


App::environment(); // test equal to App::environment('local'); App::runningInConsole(); App::runningUnitTests();


Log::info('info'); Log::info('info',array('context'=>'additional info')); Log::error('error'); Log::warning('warning'); // get monolog instance Log::getMonolog(); // add listener Log::listen(function($level, $message, $context) {}); // get all ran queries. DB::getQueryLog();


URL::full(); URL::current(); URL::previous(); URL::to('foo/bar', $parameters, $secure); URL::action('FooController@method', $parameters, $absolute); URL::route('foo', $parameters, $absolute); URL::secure('foo/bar', $parameters); URL::asset('css/foo.css', $secure); URL::secureAsset('css/foo.css'); URL::isValidUrl(''); URL::getRequest(); URL::setRequest($request); URL::getGenerator(); URL::setGenerator($generator);


Event::fire('', array($bar)); Event::listen('', function($bar){}); Event::listen('foo.*', function($bar){}); Event::listen('', 'FooHandler', 10); Event::listen('', 'BarHandler', 5); Event::listen('', function($event){ return false; }); Event::queue('foo', array($bar)); Event::flusher('foo', function($bar){}); Event::flush('foo'); Event::forget('foo'); Event::subscribe(new FooEventHandler);


DB::table('name')->get(); DB::table('name')->distinct()->get(); DB::table('name')->select('column as column_alias')->get(); DB::table('name')->where('name', '=', 'John')->get(); DB::table('name')->whereBetween('column', array(1, 100))->get(); DB::table('name')->orWhereBetween('column', array(200, 300))->get(); DB::table('name')->whereIn('column', array(1, 2, 3))->get(); DB::table('name')->whereNotIn('column', array(1, 2, 3))->get(); DB::table('name')->whereNull('column')->get(); DB::table('name')->whereNotNull('column')->get(); DB::table('name')->groupBy('column')->get(); // Default Eloquent sort is ascendant DB::table('name')->orderBy('column')->get(); DB::table('name')->orderBy('column','desc')->get(); DB::table('name')->having('count', '>', 100)->get(); DB::table('name')->skip(10)->take(5)->get(); DB::table('name')->first(); DB::table('name')->pluck('column'); DB::table('name')->lists('column'); // Joins DB::table('name')->join('table', '', '=', '') ->select('', '');
Inserts, Updates, Deletes
DB::table('name')->insert(array('name' => 'John', 'email' => '')); DB::table('name')->insertGetId(array('name' => 'John', 'email' => '')); // Batch insert DB::table('name')->insert(array( array('name' => 'John', 'email' => ''), array('name' => 'James', 'email' => '') )); // Update an entry DB::table('name')->where('name', '=', 'John') ->update(array('email' => '')); // Delete everything from a table DB::table('name')->delete(); // Delete specific records DB::table('name')->where('id', '>', '10')->delete(); DB::table('name')->truncate();
DB::table('name')->count(); DB::table('name')->max('column'); DB::table('name')->min('column'); DB::table('name')->avg('column'); DB::table('name')->sum('column'); DB::table('name')->increment('column'); DB::table('name')->increment('column', $amount); DB::table('name')->decrement('column'); DB::table('name')->decrement('column', $amount); DB::table('name')->remember(5)->get(); DB::table('name')->remember(5, 'cache-key-name')->get(); DB::table('name')->cacheTags('my-key')->remember(5)->get(); DB::table('name')->cacheTags(array('my-first-key','my-second-key'))->remember(5)->get();
Raw Expressions
// return rows DB::select('select * from users where id = ?', array('value')); // return nr affected rows DB::insert('insert into foo set bar=2'); DB::update('update foo set bar=2'); DB::delete('delete from bar'); // returns void DB::statement('update foo set bar=2'); // raw expression inside a statement DB::table('name')->select(DB::raw('count(*) as count, column2'))->get();


Model::create(array('key' => 'value')); // Find first matching record by attributes or create Model::firstOrCreate(array('key' => 'value')); // Find first record by attributes or instantiate Model::firstOrNew(array('key' => 'value')); // Create or update a record matching attibutes, and fill with values Model::updateOrCreate(array('search_key' => 'search_value'), array('key' => 'value')); // Fill a model with an array of attributes, beware of mass assignment! Model::fill($attributes); Model::destroy(1); Model::all(); Model::find(1); // Find using dual primary key Model::find(array('first', 'last')); // Throw an exception if the lookup fails Model::findOrFail(1); // Find using dual primary key and throw exception if the lookup fails Model::findOrFail(array('first', 'last')); Model::where('foo', '=', 'bar')->get(); Model::where('foo', '=', 'bar')->first(); // Find using relations Model::whereHas('relation')->get(); Model::with('relation')->where('', 'bar')->get(); // dynamic Model::whereFoo('bar')->first(); // Throw an exception if the lookup fails Model::where('foo', '=', 'bar')->firstOrFail(); Model::where('foo', '=', 'bar')->count(); Model::where('foo', '=', 'bar')->delete(); //Output raw query Model::where('foo', '=', 'bar')->toSql(); Model::whereRaw('foo = bar and cars = 2', array(20))->get(); Model::remember(5)->get(); Model::remember(5, 'cache-key-name')->get(); Model::cacheTags('my-tag')->remember(5)->get(); Model::cacheTags(array('my-first-key','my-second-key'))->remember(5)->get(); Model::on('connection-name')->find(1); Model::with('relation')->get(); Model::all()->take(10); Model::all()->skip(10); // Default Eloquent sort is ascendant Model::orderBy('column')->get(); Model::orderBy('column','desc')->get();
Soft Delete
Model::withTrashed()->where('cars', 2)->get(); // Include the soft deleted models in the results Model::withTrashed()->where('cars', 2)->restore(); Model::where('cars', 2)->forceDelete(); // Force the result set to only included soft deletes Model::onlyTrashed()->where('cars', 2)->get();
Model::creating(function($model){}); Model::created(function($model){}); Model::updating(function($model){}); Model::updated(function($model){}); Model::saving(function($model){}); Model::saved(function($model){}); Model::deleting(function($model){}); Model::deleted(function($model){}); Model::observe(new FooObserver);
Eloquent Configuration
// Disables mass assignment exceptions from being thrown from model inserts and updates Eloquent::unguard(); // Renables any ability to throw mass assignment exceptions Eloquent::reguard();


// Auto-Magic Pagination Model::paginate(15); Model::where('cars', 2)->paginate(15); // "Next" and "Previous" only Model::where('cars', 2)->simplePaginate(15); // Manual Paginator Paginator::make($items, $totalItems, $perPage); // Print page navigators in view $variable->links();


// Indicate that the table needs to be created Schema::create('table', function($table) { $table->increments('id'); }); // Specify a Connection Schema::connection('foo')->create('table', function($table){}); // Rename the table to a given name Schema::rename($from, $to); // Indicate that the table should be dropped Schema::drop('table'); // Indicate that the table should be dropped if it exists Schema::dropIfExists('table'); // Determine if the given table exists Schema::hasTable('table'); // Determine if the given table has a given column Schema::hasColumn('table', 'column'); // Update an existing table Schema::table('table', function($table){}); // Indicate that the given columns should be renamed $table->renameColumn('from', 'to'); // Indicate that the given columns should be dropped $table->dropColumn(string|array); // The storage engine that should be used for the table $table->engine = 'InnoDB'; // Only work on MySQL $table->string('name')->after('email');
$table->string('column')->unique(); $table->primary('column'); // Creates a dual primary key $table->primary(array('first', 'last')); $table->unique('column'); $table->unique('column', 'key_name'); // Creates a dual unique index $table->unique(array('first', 'last')); $table->unique(array('first', 'last'), 'key_name'); $table->index('column'); $table->index('column', 'key_name'); // Creates a dual index $table->index(array('first', 'last')); $table->index(array('first', 'last'), 'key_name'); $table->dropPrimary('table_column_primary'); $table->dropUnique('table_column_unique'); $table->dropIndex('table_column_index');
Foreign Keys
$table->foreign('user_id')->references('id')->on('users'); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'|'restrict'|'set null'|'no action'); $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade'|'restrict'|'set null'|'no action'); $table->dropForeign('posts_user_id_foreign');
Column Types
// Increments $table->increments('id'); $table->bigIncrements('id'); // Numbers $table->integer('votes'); $table->tinyInteger('votes'); $table->smallInteger('votes'); $table->mediumInteger('votes'); $table->bigInteger('votes'); $table->float('amount'); $table->double('column', 15, 8); $table->decimal('amount', 5, 2); //String and Text $table->char('name', 4); $table->string('email'); $table->string('name', 100); $table->text('description'); $table->mediumText('description'); $table->longText('description'); //Date and Time $table->date('created_at'); $table->dateTime('created_at'); $table->time('sunrise'); $table->timestamp('added_on'); // Adds created_at and updated_at columns $table->timestamps(); $table->nullableTimestamps(); // Others $table->json('options'); $table->jsonb('options'); $table->binary('data'); $table->boolean('confirmed'); // Adds deleted_at column for soft deletes $table->softDeletes(); $table->enum('choices', array('foo', 'bar')); // Adds remember_token as VARCHAR(100) NULL $table->rememberToken(); // Adds INTEGER parent_id and STRING parent_type $table->morphs('parent'); ->nullable() ->default($value) ->unsigned()


Input::get('key'); // Default if the key is missing Input::get('key', 'default'); Input::has('key'); Input::all(); // Only retrieve 'foo' and 'bar' when getting input Input::only('foo', 'bar'); // Disregard 'foo' when getting input Input::except('foo'); Input::flush();
Session Input (flash)
// Flash input to the session Input::flash(); // Flash only some of the input to the session Input::flashOnly('foo', 'bar'); // Flash only some of the input to the session Input::flashExcept('foo', 'baz'); // Retrieve an old input item Input::old('key','default_value');
// Use a file that's been uploaded Input::file('filename'); // Determine if a file was uploaded Input::hasFile('filename'); // Access file properties Input::file('name')->getRealPath(); Input::file('name')->getClientOriginalName(); Input::file('name')->getClientOriginalExtension(); Input::file('name')->getSize(); Input::file('name')->getMimeType(); // Move an uploaded file Input::file('name')->move($destinationPath); // Move an uploaded file Input::file('name')->move($destinationPath, $fileName);



Cookie::get('key'); Cookie::get('key', 'default'); // Create a cookie that lasts for ever Cookie::forever('key', 'value'); // Create a cookie that lasts N minutes Cookie::make('key', 'value', 'minutes'); // Set a cookie before a response has been created Cookie::queue('key', 'value', 'minutes'); // Forget cookie Cookie::forget('key'); // Send a cookie with a response $response = Response::make('Hello World'); // Add a cookie to the response $response->withCookie(Cookie::make('name', 'value', $minutes));



// url: Request::url(); // path: /aa/bb Request::path(); // getRequestUri: /aa/bb/?c=d Request::getRequestUri(); // Returns user's IP Request::getClientIp(); // getUri: Request::getUri(); // getQueryString: c=d Request::getQueryString(); // Get the port scheme of the request (e.g., 80, 443, etc.) Request::getPort(); // Determine if the current request URI matches a pattern Request::is('foo/*'); // Get a segment from the URI (1 based index) Request::segment(1); // Retrieve a header from the request Request::header('Content-Type'); // Retrieve a server variable from the request Request::server('PATH_INFO'); // Determine if the request is the result of an AJAX call Request::ajax(); // Determine if the request is over HTTPS Request::secure(); // Get the request method Request::method(); // Checks if the request method is of specified type Request::isMethod('post'); // Get raw POST data Request::instance()->getContent(); // Get requested response format Request::format(); // true if HTTP Content-Type header contains */json Request::isJson(); // true if HTTP Accept header is application/json Request::wantsJson();


return Response::make($contents); return Response::make($contents, 200); return Response::json(array('key' => 'value')); return Response::json(array('key' => 'value')) ->setCallback(Input::get('callback')); return Response::download($filepath); return Response::download($filepath, $filename, $headers); // Create a response and modify a header value $response = Response::make($contents, 200); $response->header('Content-Type', 'application/json'); return $response; // Attach a cookie to a response return Response::make($content) ->withCookie(Cookie::make('key', 'value'));


return Redirect::to('foo/bar'); return Redirect::to('foo/bar')->with('key', 'value'); return Redirect::to('foo/bar')->withInput(Input::get()); return Redirect::to('foo/bar')->withInput(Input::except('password')); return Redirect::to('foo/bar')->withErrors($validator); // Create a new redirect response to the previous location return Redirect::back(); // Create a new redirect response to a named route return Redirect::route('foobar'); return Redirect::route('foobar', array('value')); return Redirect::route('foobar', array('key' => 'value')); // Create a new redirect response to a controller action return Redirect::action('FooController@index'); return Redirect::action('FooController@baz', array('value')); return Redirect::action('FooController@baz', array('key' => 'value')); // If intended redirect is not defined, defaults to foo/bar. return Redirect::intended('foo/bar');



Hash::make('secretpassword'); Hash::check('secretpassword', $hashedPassword); Hash::needsRehash($hashedPassword);
// Determine if the current user is authenticated Auth::check(); // Get the currently authenticated user Auth::user(); // Get the ID of the currently authenticated user Auth::id(); // Attempt to authenticate a user using the given credentials Auth::attempt(array('email' => $email, 'password' => $password)); // 'Remember me' by passing true to Auth::attempt() Auth::attempt($credentials, true); // Log in for a single request Auth::once($credentials); // Log a user into the application Auth::login(User::find(1)); // Log the given user ID into the application Auth::loginUsingId(1); // Log the user out of the application Auth::logout(); // Validate a user's credentials Auth::validate($credentials); // Attempt to authenticate using HTTP Basic Auth Auth::basic('username'); // Perform a stateless HTTP Basic login attempt Auth::onceBasic(); // Send a password reminder to a user Password::remind($credentials, function($message, $user){});
Crypt::encrypt('secretstring'); Crypt::decrypt($encryptedString); Crypt::setMode('ctr'); Crypt::setCipher($cipher);


Mail::send('email.view', $data, function($message){}); Mail::send(array('html.view', 'text.view'), $data, $callback); Mail::queue('email.view', $data, function($message){}); Mail::queueOn('queue-name', 'email.view', $data, $callback); Mail::later(5, 'email.view', $data, function($message){}); // Write all email to logs instead of sending Mail::pretend();
// These can be used on the $message instance passed into Mail::send() or Mail::queue() $message->from('', 'Mr. Example'); $message->sender('', 'Mr. Example'); $message->returnPath(''); $message->to('', 'Mr. Example'); $message->cc('', 'Mr. Example'); $message->bcc('', 'Mr. Example'); $message->replyTo('', 'Mr. Example'); $message->subject('Welcome to the Jungle'); $message->priority(2); $message->attach('foo\bar.txt', $options); // This uses in-memory data as attachments $message->attachData('bar', 'Data Name', $options); // Embed a file in the message and get the CID $message->embed('foo\bar.txt'); $message->embedData('foo', 'Data Name', $options); // Get the underlying Swift Message instance $message->getSwiftMessage();


Queue::push('SendMail', array('message' => $message)); Queue::push('SendEmail@send', array('message' => $message)); Queue::push(function($job) use $id {}); // Same payload to multiple workers Queue::bulk(array('SendEmail', 'NotifyUser'), $payload); // Starting the queue listener php artisan queue:listen php artisan queue:listen connection php artisan queue:listen --timeout=60 // Process only the first job on the queue php artisan queue:work // Start a queue worker in daemon mode php artisan queue:work --daemon // Create migration file for failed jobs php artisan queue:failed-table // Listing failed jobs php artisan queue:failed // Delete failed job by id php artisan queue:forget 5 // Delete all failed jobs php artisan queue:flush


Validator::make( array('key' => 'Foo'), array('key' => 'required|in:Foo') ); Validator::extend('foo', function($attribute, $value, $params){}); Validator::extend('foo', 'FooValidator@validate'); Validator::resolver(function($translator, $data, $rules, $msgs) { return new FooValidator($translator, $data, $rules, $msgs); });
accepted active_url after:YYYY-MM-DD before:YYYY-MM-DD alpha alpha_dash alpha_num array between:1,10 confirmed date date_format:YYYY-MM-DD different:fieldname digits:value digits_between:min,max boolean email exists:table,column image in:foo,bar,... not_in:foo,bar,... integer numeric ip max:value min:value mimes:jpeg,png regex:[0-9] required required_if:field,value required_with:foo,bar,... required_with_all:foo,bar,... required_without:foo,bar,... required_without_all:foo,bar,... sometimes|required|field same:field size:value timezone unique:table,column,except,idColumn url


View::make('path/to/view'); View::make('foo/bar')->with('key', 'value'); View::make('foo/bar')->withKey('value'); View::make('foo/bar', array('key' => 'value')); View::exists('foo/bar'); // Share a value across all views View::share('key', 'value'); // Nesting views View::make('foo/bar')->nest('name', 'foo/baz', $data); // Register a view composer View::composer('viewname', function($view){}); //Register multiple views to a composer View::composer(array('view1', 'view2'), function($view){}); // Register a composer class View::composer('viewname', 'FooComposer'); View::creator('viewname', function($view){});

Blade Templates

@extends('') // Begin a section @section('name') // End a section @stop // End a section and yield @show @parent // Show a section in a template @yield('name') @include('') @include('', array('key' => 'value')); @lang('') @choice('', 1); @if ( $foo == $bar ) @else @elseif @endif @unless @endunless @for ( $i = 0 ; $i < 100 ; $i++ ) @endfor @foreach ( $vars as $var ) @endforeach @while @endwhile //forelse 4.2 feature @forelse($users as $user) @empty @endforelse // Echo content {{ $var }} // Echo escaped content {{{ $var }}} {{-- Blade Comment --}} // Echoing Data After Checking For Existence {{{ $name or 'Default' }}} // Echo HTML content {!! $html or 'Foo' !!} // Displaying Raw Text With Curly Braces @{{ This will not be processed by Blade }}


Form::open(array('url' => 'foo/bar', 'method' => 'PUT')); Form::open(array('route' => '')); Form::open(array('route' => array('', $parameter))); Form::open(array('action' => 'FooController@method')); Form::open(array('action' => array('FooController@method', $parameter))); Form::open(array('url' => 'foo/bar', 'files' => true)); Form::close(); Form::token(); Form::model($foo, array('route' => array('', $foo->bar)));
Form Elements
Form::label('id', 'Description'); Form::label('id', 'Description', array('class' => 'foo')); Form::text('name'); Form::text('name', $value); Form::text('name', $value, array('class' => 'name')); Form::textarea('name'); Form::textarea('name', $value); Form::textarea('name', $value, array('class' => 'name')); Form::hidden('foo', $value); Form::password('password'); Form::password('password', array('placeholder' => 'Password')); Form::email('name', $value, array()); Form::file('name', array('class' => 'name')); Form::checkbox('name', 'value'); // Generating a checkbox that is checked Form::checkbox('name', 'value', true, array('class' => 'name')); Form::radio('name', 'value'); // Generating a radio input that is selected Form::radio('name', 'value', true, array('class' => 'name')); Form::select('name', array('key' => 'value')); Form::select('name', array('key' => 'value'), 'key', array('class' => 'name')); Form::selectRange('range', 1, 10); Form::selectYear('year', 2011, 2015); Form::selectMonth('month'); Form::submit('Submit!', array('class' => 'name')); Form::button('name', array('class' => 'name')); Form::macro('fooField', function() { return '<input type="custom"/>'; }); Form::fooField();

HTML Builder


// Transliterate a UTF-8 value to ASCII Str::ascii($value) Str::camel($value) Str::contains($haystack, $needle) Str::endsWith($haystack, $needles) // Cap a string with a single instance of a given value. Str::finish($value, $cap) Str::is($pattern, $value) Str::length($value) Str::limit($value, $limit = 100, $end = '...') Str::lower($value) Str::words($value, $words = 100, $end = '...') Str::plural($value, $count = 2) // Generate a more truly "random" alpha-numeric string. Str::random($length = 16) // Generate a "random" alpha-numeric string. Str::quickRandom($length = 16) Str::upper($value) Str::title($value) Str::singular($value) Str::slug($title, $separator = '-') Str::snake($value, $delimiter = '_') Str::startsWith($haystack, $needles) // Convert a value to studly caps case. Str::studly($value) Str::macro($name, $macro)


App::setLocale('en'); Lang::get('messages.welcome'); Lang::get('messages.welcome', array('foo' => 'Bar')); Lang::has('messages.welcome'); Lang::choice('messages.apples', 10); // Lang::get alias trans('messages.welcome');


File::exists('path'); File::get('path'); File::getRemote('path'); // Get a file's contents by requiring it File::getRequire('path'); // Require the given file once File::requireOnce('path'); // Write the contents of a file File::put('path', 'contents'); // Append to a file File::append('path', 'data'); // Delete the file at a given path File::delete('path'); // Move a file to a new location File::move('path', 'target'); // Copy a file to a new location File::copy('path', 'target'); // Extract the file extension from a file path File::extension('path'); // Get the file type of a given file File::type('path'); // Get the file size of a given file File::size('path'); // Get the file's last modification time File::lastModified('path'); // Determine if the given path is a directory File::isDirectory('directory'); // Determine if the given path is writable File::isWritable('path'); // Determine if the given path is a file File::isFile('file'); // Find path names matching a given pattern. File::glob($patterns, $flag); // Get an array of all files in a directory. File::files('directory'); // Get all of the files from the given directory (recursive). File::allFiles('directory'); // Get all of the directories within a given directory. File::directories('directory'); // Create a directory File::makeDirectory('path', $mode = 0777, $recursive = false); // Copy a directory from one location to another File::copyDirectory('directory', 'destination', $options = null); // Recursively delete a directory File::deleteDirectory('directory', $preserve = false); // Empty the specified directory of all files and folders File::cleanDirectory('directory');


app_path(); // Get the path to the public folder public_path(); // App root path base_path(); // Get the path to the storage folder storage_path();
// Convert a value to camel case camel_case($value); // Get the class "basename" of the given object / class class_basename($class); // Escape a string e('<html>'); // Determine if a given string starts with a given substring starts_with('Foo bar.', 'Foo'); // Determine if a given string ends with a given substring ends_with('Foo bar.', 'bar.'); // Convert a string to snake case snake_case('fooBar'); // Determine if a given string contains a given substring str_contains('Hello foo bar.', 'foo'); // Result: foo/bar/ str_finish('foo/bar', '/'); str_is('foo*', 'foobar'); str_plural('car'); str_random(25); str_limit($value, $limit = 100, $end = '...') str_singular('cars'); // Result: FooBar studly_case('foo_bar'); trans(''); trans_choice('', $count);
URLs and Links
action('FooController@method', $parameters); link_to('foo/bar', $title, $attributes, $secure); link_to_asset('img/foo.jpg', $title, $attributes, $secure); link_to_route('', $title, $parameters, $attributes); link_to_action('FooController@method', $title, $params, $attrs); // HTML Link asset('img/photo.jpg', $title, $attributes); // HTTPS link secure_asset('img/photo.jpg', $title, $attributes); secure_url('path', $parameters); route($route, $parameters, $absolute = true); url('path', $parameters = array(), $secure = null);

Unit testing

Install and run
// add to composer and update: "phpunit/phpunit": "4.0.*" // run tests (from project root) ./vendor/bin/phpunit
Calling routes


Executing Commands
SSH::run(array $commands); SSH::into($remote)->run(array $commands); // specify remote, otherwise assumes default SSH::run(array $commands, function($line) { echo $line.PHP_EOL; });
SSH::define($taskName, array $commands); // define SSH::task($taskName, function($line) // execute { echo $line.PHP_EOL; });
SFTP Uploads
SSH::put($localFile, $remotePath); SSH::putString($string, $remotePath);
Filesystem/Cloud Storage
Storage::disk('s3'); Storage::disk('local')->put('file.txt', 'Contents'); Storage::disk('local')->get('file.jpg'); Storage::disk('s3')->exists('file.jpg'); Storage::get('file.jpg'); Storage::put('file.jpg', $contents); Storage::size('file1.jpg'); Storage::lastModified('file1.jpg'); Storage::copy('old/file1.jpg', 'new/file1.jpg'); Storage::move('old/file1.jpg', 'new/file1.jpg'); Storage::prepend('file.log', 'Prepended Text'); Storage::append('file.log', 'Appended Text'); Storage::delete(['file1.jpg', 'file2.jpg']); Storage::files($directory); Storage::allFiles($directory); Storage::directories($directory); Storage::allDirectories($directory); Storage::makeDirectory($directory); Storage::deleteDirectory($directory);


Leave a Reply

Your email address will not be published. Required fields are marked *