Skip to content

Instantly share code, notes, and snippets.

@hr-sadooghi
Created May 20, 2017 17:14
Show Gist options
  • Save hr-sadooghi/b778609f0594bb589aaa3d976cfbe6aa to your computer and use it in GitHub Desktop.
Save hr-sadooghi/b778609f0594bb589aaa3d976cfbe6aa to your computer and use it in GitHub Desktop.
laravel-notes

Laravel Notes

  • make model & controller & migration with one command:
php artisan make:model Post -mc
  • create only Controller for resource(CRUD actions)
php artisan make:controller TasksController -r
  • To add hidden CSRF field in blade file(template) use:
{{ csrf_field() }}

###Migration tips

  • Build tables from migration files. or check connection settings:
php artisan migrate

In laravel table name is plural by default, and Model name is singular.

Usage:
  make:migration [options] [--] <name>

Arguments:
  name                   The name of the migration.

Options:
      --create[=CREATE]  The table to be created.
      --table[=TABLE]    The table to migrate.
Help:
  Create a new migration file

php artisan make:migration {migration-file-name} --create={table-name}
php artisan make:migration create_tasks_table --create=tasks

When you delete migration file, this error occurred:

failed to open strem: No such file or directory

To fix it run:

composer dump-autoload

To apply changes that we have made in migration files run:

php artisan migrate:refresh

This command rollback migration and run them again.

###Laravel Query Builder

//return all of data in the tasks table.
$list = DB::table('tasks')->get();

//return data with condition
$list = DB::table('tasks')->where('created_at', '>=', 'NOW()')->get();

//order to latest data in first
$list = DB::table('tasks')->latest()->get();

//find one item by primary key
$item = DB::table('tasks')->find($id);

####Run laravel interactive shell

php artisan tinker
//return only body field of records in one  dimensional array.
App\Task::pluck('body');
App\Task::pluck('body')->first();

rollback all applied migration

php artisan migrate:reset

php artisan make:model Post model name is singular and table name is plural. model: Post, table: posts

App\Task::where('completed', 1)->get(); completed field is boolean

###Mass assignment

{ModelClassName}::create(assoc array of data);

data: assoc array with key as a field and value as data to insert

Before using mass assignment we need to prepare model class by using this property override In Model Class:

protected $fillable = ['field1', 'field2'];

Or in inverse side:

these fields cannot be used with create method in mass assignment.

protected $guarded = ['field3', 'field4'];

###Validation

$this->validate(request(), ['title'=>'required|min:3|max:120'];

To access list of errors in anywhere like blade, we can use this command to access array list of errors:

$errors->all()

contain list of validation errors.

###Table Relations

In model class:

public function comments(){
	return $this->hasMany(Comment:class);
}

In other side model class:

public function post(){
	return $this->belongsTo(Post:class);
}

In tinker we can test it: //run tinker php artisan tinker $post = App\Post::find(6); //rather than it's a method we can use it as a property. to fetch comments of post $post->comments

$c = App\Comment::first(); $c->post;

To set method other than get and post we use method field in in form:

{{ method_field('PATCH') }}

After storing form data to return to previous page use this helper function:

return back();

php artisan down php artisan up

to use middleware in the controller constructor: $this->middleware('auth', ['only'=>'index']); //or $this->middleware('auth', ['except'=>'index']);

###Service

App::bind('App\Billing\Stripe', function() {
    return new \App\Billing\Stripe(config(services.stripe.secret));
});

$stripe = App::make('App\Billing\Stripe');
//or
$stripe = resolve('App\Billing\Stripe');
//or
$stripe = app('App\Billing\Stripe');

Or if you want you return only one instance of class:

App::singleton('App\Billing\Stripe', function() {
    return new \App\Billing\Stripe(config(services.stripe.secret));
});

//All of them refer to one inctance.
$stripe1 = resolve('App\Billing\Stripe');
$stripe2 = resolve('App\Billing\Stripe');
$stripe3 = resolve('App\Billing\Stripe');

###Insert Data into a table

$post = new App\Post;
$post->title = request('title');
$post->body = request('body');
$post->save();

//or this way(mass assignment):
Post::create([
    'title'=>request('title'),
    'body'=>request('body'),
]);

//but has mass assignment excetion, to solve it,
//in the model class override this property:

//list of fields to allow in mass assignment
protected $fillable = ['title', 'body'];

//or very simpler:
Post::create(request()->all());

//finally redirect
return redirect('/');

###Input Validation In the controller method call:

$this->validate(request(), [
    'title'=>'required',
    'body'=>'required|min:3'
]);

In error condition automatically redirect to previous page and populate error messages into errors variable.

Display validation errors

to display validation errors in the blade use:

@if (count($errors))
<div class="alert alert-danger">
    <ul>
        @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>
        @endforeach
    </ul>
</div>
@endif

Get list of records that ordered by created_at filed asc

$post = Post::orderBy('created_at', 'asc')->get();
//or simpler
$post = Post::latest()->get()

composer.json manage php dependencies package.json manage node dependencies

npm run dev

npm run watch

This helper command login specified user:

auth()->login($user);

this helper used to redirect user to specified route name. home is the route name that we choose for some controller.

return redirect()->home();

To assign a name to the route we use:

Route::get('/', 'IndexController@index')->name('home');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment