8/14/2017 - 6:29 PM

Laravel Notes

Laravel Notes


- Install a new Laravel project via composer: 
composer create-project laravel/laravel laraveltest --prefer-dist

if you get a 500 server error related to 'storage' directory when going to the project URL:
chmod -R 777 storage

- To create a new controller:
php artisan make:controller PagesController

in our web.php file we specify the routes, for /new route

// METHOD 1 simple view with no data passed to the used View
// this route does not specify a controller, it just displays a view "new.blade.php"
Route::get('/new', function () {
 	return view('new') ;
 }) ;

// METHOD 2: array form that specifies controller and @ method
// this route specifies a PagesController that uses 'new' method
Route::get('/new', [
	'uses' => 'PagesController@new'
]) ;

The PagesController that was created with php artisan will look like:


namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PagesController extends Controller
    public function new() {
    	return view('new') ;

- *********  To create a new Model ****************
 php artisan make:model Todo -m

this will create a file in /database/migrations

Now in that file you can enter the database table columns

public function up() {
	Schema::create('todos', function (Blueprint $table ) {
		$table->increments('id') ;
		$table->string('todo') ;
		$table->boolean('completed')->default(0) ;
		$table->timestamps() ;

After you have the fields that you wanted to put in your migrations file, execute the migration table so Laravel can migrate this data to the actual Database table

php artisan migrate

- ************** To create Seeders *******************

edit /database/factories/ModelFactory.php


// note we only need the field of todo to be filled with 10 words,
// all others are automatically incremented or have default Database values

$factory->define(App\Todo::class, function(Faker\Generator $faker) {
	return [
		'todo' => $faker->sentence(10)
	] ;

Now Create a TodosTableSeeder:
 php artisan make:seeder TodosTableSeeder

Open /database/seeds/TodosTableSeeder.php

with the following contents:
    public function run()
        // create 7 new Todos
        // Now define this table seeder in DatabaseSeeder.php
        factory(App\Todo::class , 7 )->create() ;  

Edit database/seeds/DatabaseSeeder.php and put
    public function run()
        // $this->call(UsersTableSeeder::class);
        // Define the TodosTableSeeder class
        $this->call(TodosTableSeeder::class) ;

Now run the db seed artisan command
php artisan db:seed

- Now look at your DB table with the fake data that was generated

- ****************  Pass data to our View  *********************
for example to pass data from the database from our controller to the view:


namespace App\Http\Controllers;

use App\Todo; // use to interact with our Todos database
use Illuminate\Http\Request;

class TodosController extends Controller {
    public function index() {
    	$todos = Todo::all() ;
    	// Method 1
    	//return view('todos', compact('todos') ) ;
    	// Method 2
    	 return view('todos')->with('todos', $todos) ;

and in our todos.blade.php

    @foreach ( $todos as $todo)

     <li>{{ $todo->todo }}</li>

- **************   CREATE VIEW LAYOUTS ****************

1) create a  main layout blade template:  layout.blade.php

<!doctype html>
<html lang="{{ app()->getLocale() }}">
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">


<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">


            <div class="content">
                <div class="title m-b-md">
  				This is where all the content from other pages will be shown, using this layout we prevent repeating the header and footer section



<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

- Now create a new blade template:  todos.blade.php:


    <h1>Create a new Todo</h1>

    <input class="form-control input" type="text" name="todo">

    <h1>List of Todos</h1>

    @foreach ( $todos as $todo)

     <li>{{ $todo->todo }}</li>


Here we have the content that will be show using the layout file as the main template and inject all the content from @section('content')
through @stop

- ************ NOW THE CRUD ****************
start with the [C]reate

in our TodosController.php

public function store( Request $request ) {
	// debug:
	// dd( $request->all() ) ;
	$todoObj = new Todo ;
	// $todoObj->todo refers to the todo column
	$todoObj->todo = $request->todo ; // gets todo from the form
	$todoObj->save() ; // saves to the database

	return redirect()->back() ;


in our web.php Routes:

Route::post('/create/todo', [
	'uses' => 'TodosController@store'
]) ;

-------------------- Delete ----------------------

// CRU[D] in TodosController.php
public function delete ($id) {
	$todoObj = Todo::find($id) ;
	$todoObj->delete() ;
	return redirect()->back() ;

// in web.php
Route::get('/todo/delete/{id}', [
	'uses' => 'TodosController@delete',
	// this is an alias that will be used in our view
	'as'   => 'todo.delete'
]) ;

in our View
    @foreach ( $todos as $todo)

     <li>{{ $todo->todo }} <a href="{{ route('todo.delete', ['id' => $todo->id]) }}" class="btn btn-danger"> x </a></li>

---------------------- Update ---------------------
in TodosController.php
    // CR[U]D   ===========> SEND TO UPDATE VIEW
    public function update ($id) {
    	$todo = Todo::find($id) ;
    	// Here we are sending the user to a new view "update"  with $todo data as the ID 
    	// this is not taking any action yet in the database, thats is the job for the "save"  method
    	return view('update')->with('todo', $todo) ;

    // CR[U]D  =============> POST THE UPDATE
    public function save(Request $request, $id) {
    	$todo = Todo::find($id) ;
    	$todo->todo = $request->todo;
    	$todo->save() ;
    	// return redirect()->back() ;
    	return redirect()->route('todos') ; // todos alias is defined in web.php in the /todos route