Showing posts with label laravel. Show all posts
Showing posts with label laravel. Show all posts

Tuesday, 21 November 2017

Bootstrap 4 Laravel Preset for Laravel 5.5

You can start using Bootstrap 4 beta with Laravel 5.5 with our new Bootstrap 4 frontend preset. The preset includes scaffolding for SCSS files, and imports Bootstrap 4 JavaScript plugins, jQuery, and Popper.js. As of this writing, we keep the jQuery dependency that ships with Laravel, but according to the Bootstrap documentation the jQuery slim version could be used instead.
The Bootstrap 4 preset resembles the current Bootstrap 3 scaffolding that ships with Laravel by default, with Bootstrap 4 variables and markup that give you a good starting point. When the final version of Bootstrap 4 is released, you will be able to update your project (relatively) smoothly.

How Does the Preset Work?

Laravel 5.5 ships with a preset command that gives you the ability to change frontend scaffolding or even delete it. Our package registers two presets, bootstrap4, and bootstrap4-auth, to provide you with more flexibility if you don’t want the auth views.
When you run the Bootstrap 4 preset command, it will remove the bootstrap-sassnode module, and add bootstrap and popper.js node modules. Our preset bootstrap.js is the same as the default, except for a global Popper.js import, which is a new dependency for various Bootstrap 4 JavaScript plugins.
The app.scss file keeps the Raleway Google font, and imports an updated _variables.scss file that gives you a good starting point for your custom CSS.
// Fonts
@import url("https://fonts.googleapis.com/css?family=Raleway:300,400,600");

// Variables
@import "variables";

// Bootstrap
@import "~bootstrap/scss/bootstrap";
I’ve gone through the _variables.scss file and ported over some of the variables from the default Laravel version, and removed variables that are no longer relevant. For example, the panel component no longer exists in Bootstrap 4, and we’ve removed the associated variables. The variables file is a starting point that you can easily modify, and I’d recommend you learn more from Bootstrap’s theming documentation.

Installing the Bootstrap 4 Frontend Preset

With the new package auto-discovery installing the Laravel Bootstrap 4 preset couldn’t be simpler:
composer require laravelnews/laravel-twbs4
php artisan preset bootstrap4-auth
yarn && yarn dev
If you don’t need the auth views, you can install the preset like the following:
composer require laravelnews/laravel-twbs4
php artisan preset bootstrap4
yarn && yarn dev

Learn More

Check out our official repository to get started and if you notice any issues or something missing in our Bootstrap 4 preset, feel free to raise an issue or submit a pull request.
Bootstrap 4 is still a beta version (our preset uses Bootstrap 4 Beta 2), and a few breaking changes will be coming to Beta 3. After Beta 3 is released, the next release is the final release of Bootstrap 4!

Monday, 13 November 2017

Setup Bootstrap Sass with Laravel Elixir

Laravel Elixir is a fantastic package that simplifies working with Gulp. For the unfamiliar Gulp is a JavaScript task runner that allows you to automate tasks. It can be used for compiling CSS, concating and minifying JavaScript, and much more.
Gulp was designed to be faster than previous build tools by utilizing node streams and has become one of the go to build systems. Laravel Elixir is a wrapper around Gulp making the setup a breeze.
In this tutorial let’s take a look at how to setup Bootstrap Sass with Elixir in a default Laravel 5.1 install.

Installing NPM Dependencies

Both Bootstrap and Elixir are node packages that are available via NPM, node package manager. If you open up the default package.json file you will see a list of dependencies:
"dependencies": {
    "laravel-elixir": "^3.0.0",
    "bootstrap-sass": "^3.0.0"
}
From terminal, run npm install and both these packages will be installed as well as any of their dependencies. If you are familiar with composer for PHP then it’s almost identical.
After the command finishes running, you can look in the node_modules folder and see a list of all the packages.

Bootstrap Sass

Implementing Bootstrap into your project is now simple. Open resources/assets/sass/app.scss and uncomment this line:
@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";
Save it and run gulp, then you have all the Bootstrap styles ready for you to use. That’s literally all that is required.

Customizing Bootstrap Styles

If you are not happy with the default Bootstrap design you can easily customize it by overriding its variables. As an example let’s change the default font to Lato from Google Fonts.
Open resources/assets/sass/app.scss again and we can import the font and adjust the variable. Here is the whole file with these changes:
@import url(https://fonts.googleapis.com/css?family=Lato);
$font-family-sans-serif: 'Lato', sans-serif;
@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";
How this works is first we import the Lato font from Google. Next, we override Bootstrap’s existing variable for font-family. This works because Bootstrap uses the Saas !default. Here is how they describe it:
You can assign to variables if they aren’t already assigned by adding the !default flag to the end of the value. This means that if the variable has already been assigned to, it won’t be re-assigned, but if it doesn’t have a value yet, it will be given one.
To find a list of all the variables you can customize open:

node_modules/bootstrap-sass/assets/stylesheets/bootstrap/_variables.scss

Including Bootstrap JavaScript with Browserify

For including the Bootstrap JavaScript we have a few options. We could use their CDN, download it manually, or use a system called Browserify.
Browserify lets you require(‘modules’) in the browser by bundling up all of your dependencies.
Because we already have Bootstrap installed through NPM we can utilize browserify and pull these into our app.js file. First, we do need to install jQuery and let’s do it through NPM by running the following command:
npm install jquery --save
Now, create the following file: resources/assets/js/app.js and add the following code:
window.$ = window.jQuery = require('jquery')
require('bootstrap-sass');

$( document ).ready(function() {
    console.log($.fn.tooltip.Constructor.VERSION);
});
Bootstrap expects jQuery to be global and with the first line we are including jQuery and assigning it to the window. The second line is requiring Bootstrap JavaScript. The last section is just a jQuery on ready and logging out the bootstrap tooltip version. This is used to just confirm it’s loading as we expect.
Now, lets modify the gulpfile.js in the project root:
elixir(function(mix) {
    mix.sass('app.scss')
        .browserify('app.js');
});
The simplicity of this shows just how great Elixir is. By just adding .browserify('app.js') everything is handled automatically. After saving run gulpagain and this will be compiled into public/js/app.js
If you include this in your layout and load the site in a browser you should see 3.3.5showing in the console.

Sunday, 5 November 2017

Laravel new Features in Blade If Directives

A new Blade addition in Laravel 5.5 will add support for simplifying custom ifstatements in your views.
The syntax might something like this in your AppServiceProvider::boot()method:
use Illuminate\Support\Facades\Blade;

Blade::if('admin', function () {
    return auth()->check() && auth()->user()->isAdmin();
});
The new Blade::if() makes it convenient to abstract repetitive checks out of templates, making them more readable:
@admin
    <a href="{{ route('super.secret') }}">Secret Page</a>
@else
    Welcome Guest. <a href="{{ route('login') }}">Login</a>
@endadmin
In previous versions of Laravel, you would have to write a bit more code. For example, David Hemphill tweeted some really cool directives using this technique in Laravel 5.4:
//AppServiceProvide
Blade::directive('prod',function($beta){
 return "<?php if(app()->environment('production')):?>";
});
Blade::directive('endprod',function($beta){
 return "<?php endif; ?>";
});

-----------------------------------
//In your blade template
@prod
<script src="some-production-only-script" async></script>
@endprod
Which is now simplified even more in Laravel 5.5:
Blade::if('prod', function () {
    return app()->environment('production');
});
You can also pass arguments to make the checks more dynamic:
Blade::if('env', function ($env) {
    return app()->environment($env);
});
Which would then look like this in your templates:
@env('production')
  <script src="some-prod.js"></script>
@endenv
If you want to learn more about Blade::if(), Laracasts has a video tutorial on it, and we look forward to seeing what you’ll come up with!

Laravel new Features in Routing methods in laravel

Laravel 5.5 shipped a couple of convenient shortcuts to the Laravel Router class that eliminates the need for creating a controller or closure only to return a simple view or redirect.

1. Route::view
2. Route::redirect

Here we will see clear information regarding route functions.


The Route::view method

The Route::view method eliminates the need for routes that only need a view returned. Instead of using a controller or a closure, you can define a URI and a path to a view file:


// resources/views/pages/about.blade.php
Route::view('/about', 'pages.about');
You can also pass in an array of variables that will be passed to the view:
Route::view('/about', 'pages.about', ['year' => date('Y')]);
The Route::redirect Method


The Route::redirect method also eliminates the need to create a controller or a closure only to return a redirect response:
Route::redirect('/homepage', '/home');
The third default argument, if not passed, is a 301 redirect. However, you can pass the third argument for a different status code. For example, if you want to create a 307 Temporary Redirect, it would look like this:
Route::redirect('/homepage', '/home', 307);

Tuesday, 28 March 2017

Create, Edit, Update and Destroy functionality using Laravel 5.3

In this tutorial we will create basic CRUD functionality (Create, Edit, Update and Delete) using Laravel 5.3. There are a few changes done in the latest version of Laravel 5.3 that I found that broke my earlier code. Many tutorials that are available online are not up to date and were not much helpful so I decided to write a tutorial.

First of all we will have to create a resource route in your routes/web.php. This is one of the change in Laravel 5.3: In earlier versions there was just one routes.php file but in Laravel 5.3 the routes have been split into three files.

Note that I am adding this route to resource controller for an admin section.

------------------------------------------------------------------------------------
Route::group(['prefix' => 'admin'], function () {
  ...
  Route::resource('/categories', 'admin\CategoryController');
  ...
});

----------------------------------------------------------------

we have to install a package using composer to make HTML and FORM functionality work. Laravel 5.3 does not come with HTML and FORM package installed.

-------------------------------------------------------------------------
composer require "laravelcollective/html":"^5.2.0"
-------------------------------------------------------------------------

Next in the config/app.php we have to add the following providers and aliases at the end of each arrays like shown below:

------------------------------------------------------------
'providers'[

Collective\Html\HtmlServiceProvider::class,
],


'aliases' => [

'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
'Input' => Illuminate\Support\Facades\Input::class,

],

------------------------------------------------------------

Next, We will have to create a controller using the following PHP artisan command in the command line editor. Make sure you are creating this inside your project directory.

------------------------------------------------------------

php artisan make:controller CategoryController --resource
------------------------------------------------------------

This command will create a Category resource controller with a few empty functions/methods such as index, create, edit, update, show and destroy. Note that these are REST functions.
The file will be created in Http/Controllers/CategoryController.php but we need this in the admin section so we will have to create a simple admin folder inside Controllers directory and move the CategoryController.php inside the admin/ folder.

In doing this we have changed its location so now we have to change the namespace as well. The namespace now changes from:



------------------------------------------------------------
namespace App\Http\Controllers;
To

namespace App\Http\Controllers\admin;


------------------------------------------------------------

Remember also to add the following entities and classes at the top of the file

------------------------------------------------------------
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Category;
use Validator;
use DB, Session, Crypt, Hash;
use Illuminate\Support\Facades\Input;
------------------------------------------------------------

Now, since this is an admin section I want to make sure that only the logged in user can access this page. To do this we will have to add authentication code inside our constructor in the CategoriesController.php page. You can also write a middleware to achieve this.

------------------------------------------------------------

public function __construct()
{
$this->middleware('auth');
}


------------------------------------------------------------


The Index() function

The below code needs to be added to the index function. The index function will handle listing of the categories along with the edit and delete buttons.

------------------------------------------------------------

public function index()
{
    // get all the categories
    $categories = DB::table('categories')->paginate(15);
    // load the view and pass the categories
    return view('admin.category.index', ['categories' => $categories]);
}

------------------------------------------------------------



We are simply querying the categories table and trying to paginate the results. The DB::table(‘categories’) part will fetch all the categories and the paginate function will paginate the results in 15 records each.

Next, We have to send the results to the view file. Usually view files goes inside resources/views/ directory but since this is an admin section we have to create a separate admin directory inside resources/views and add all the admin views inside it. So for CategoryController.php the views will be in resources/views/admin/category/ folder.
Lets have a closer look to the following line that we added in the controller.

------------------------------------------------------------

return view('admin.category.index', ['categories' => $categories]);
------------------------------------------------------------



We are going to send $categories array to admin/category/index.blade.php file. We use a dot notation to separate the directory.

This is what the index.blade.php looks like:

---------------------------------------------------------------
@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row">
        <h1>All Categories</h1>
        <div><a href="{{ URL::to('admin/categories/create') }}">Create a Category</a></div>
        <!-- will be used to show any messages -->
        @if (Session::has('message'))
            <div class="alert alert-info">{{ Session::get('message') }}</div>
        @endif
        <table class="table table-striped table-bordered">
            <thead>
                <tr>
                    <td>ID</td>
                    <td>Category name</td>
                    <td>Actions</td>
                </tr>
            </thead>
            <tbody>
            @foreach($categories as $key => $value)
                <tr>
                    <td>{{ $value->id }}</td>
                    <td>{{ $value->name }}</td>
                    <td>
                        <a class="btn btn-small btn-info" href="{{ URL::to('admin/categories/' . $value->id . '/edit') }}">Edit</a>
                        {{ Form::open(array('url' => 'admin/categories/' . $value->id, 'class' => 'btn btn-small')) }}
                            {{ Form::hidden('_method', 'DELETE') }}
                            {{ Form::submit('Delete', array('class' => 'btn btn-danger')) }}
                        {{ Form::close() }}
                    </td>
                </tr>
            @endforeach
            {{ $categories->links() }}
            </tbody>
        </table>
    </div>
</div>
@endsection
---------------------------------------------------------------
We are extending the default Laravel layouts.app. To generate pagination links the following code needs to be added to the index.blade.php file.

-----------------------------------------------------------


{{ $categories->links() }}
-----------------------------------------------------------


The create() function

The create function will just display the view at resources/views/admin/category/create.blade.php



-----------------------------------------------------------
public function create()
{
    return view('admin.category.create');

}

-----------------------------------------------------------

And the create.blade.php file looks like:


-----------------------------------------------------------
@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row">
         
        <h1>Create a Category</h1>
         
        <!-- show errors -->
        @if (count($errors) > 0)
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif
        {{ Form::open(array('url' => 'admin/categories')) }}
            <div class="form-group">
                {{ Form::label('name', 'Name') }}
                {{ Form::text('name', Input::old('name'), array('class' => 'form-control')) }}
            </div>
            {{ Form::submit('Create Category!', array('class' => 'btn btn-primary')) }}
        {{ Form::close() }}
    </div>
</div>
@endsection
-----------------------------------------------------------

The store() function

The store function will validate the input and store the data in the categories table.


-----------------------------------------------------------

public function store(Request $request)
{
    // validate
    // read more on validation at http://laravel.com/docs/validation
    $rules = array(
        'name'       => 'required',
    );
    $validator = Validator::make(Input::all(), $rules);
    $this->validate($request, [
        'name' => 'required'
    ]);
    if ($validator->fails()) {
        return redirect('admin/categories/create')
                    ->withErrors($validator)
                    ->withInput();
    } else {
        // store
        $category = new Category;
        $category->name = Input::get('name');
        $category->visible = 1;
        $category->save();
        // redirect
        Session::flash('message', 'Successfully created Category!');
        return redirect('admin/categories');
         
    }
}
-----------------------------------------------------------

The edit() function

The edit function displays the existing data in the input fields. It uses the layout resources/views/admin/category/edit.blade.php

-----------------------------------------------------------
public function edit($id)
{
    // get the category
    $category = Category::find($id);
    // show the edit form and pass the category
    return view('admin.category.edit')
    ->with('category', $category);

}

-----------------------------------------------------------
…and the edit.blade.php view looks like below:

-----------------------------------------------------------

@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row">
        <h1>Edit {{ $category->name }}</h1>
        {{ Form::model($category, array('route' => array('categories.update', $category->id), 'method' => 'PUT')) }}
            <div class="form-group">
                {{ Form::label('name', 'Name') }}
                {{ Form::text('name', null, array('class' => 'form-control')) }}
            </div>
            {{ Form::submit('Edit the Category!', array('class' => 'btn btn-primary')) }}
        {{ Form::close() }}
    </div>
</div>
@endsection
-----------------------------------------------------------

The update() function

The update function will update the existing category.

-------------------------------------------------------------

public function update($id, Request $request)
{
    // validate
    // read more on validation at http://laravel.com/docs/validation
    $rules = array(
        'name'  => 'required',
    );
    $validator = Validator::make(Input::all(), $rules);
    $this->validate($request, [
        'name' => 'required'
    ]);
    if ($validator->fails()) {
        return redirect('admin/categories/create')
                    ->withErrors($validator)
                    ->withInput();
    } else {
        // store
        $category = Category::find($id);
        $category->name = Input::get('name');
        $category->visible = 1;
        $category->save();
        // redirect
        Session::flash('message', 'Successfully updated category!');
        return redirect('admin/categories');
         
    }

}
-------------------------------------------------------------

Finally the destroy() function

The destroy function deletes a category from the categories table.

-------------------------------------------------------------
public function destroy($id)
{
    // delete
    $category = Category::find($id);
    $category->delete();
    // redirect
    Session::flash('message', 'Successfully deleted the category!');
    return redirect('admin/categories')->with('status', 'Category Deleted!');
}
-------------------------------------------------------------

cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) in Laravel

  WampServer: Download this file:  http://curl.haxx.se/ca/cacert.pem Place this file in the  C:\wamp64\bin\php\php7.1.9  folder Open  php.in...

Popular Articles