1)ROUTING
In Laravel, the routing rules for application is written in routes/web.php file. Here in Laravel 2 new types of methods has been introduced put and patch.so lets check how we can use those in routes.
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);
In Practical Cases:-
Route::get('cms/list','CmsController@list');
Here if the request comes for cms/list, it will go to CmsController and run the method list(). And you can see its a get request declared.
Consider If you want to store some data, then you have to call that particular method like:-
Route::post('cms/savepost','CmsController@savepost');
Consider if you want to edit a post, the ids passed will be dynamic. so the route will be like:-
Route::get('cms/edit/{id?}','CmsController@edit');
And in edit method you can retrieve id as parameter and do the operations.
2) TERMINAL ACCESSS
In Laravel , you can make use of the inbuilt terminal come with that for performing many operations. For this you should have composer installed and configured PHP path. that you can search for how to do that. you can download and install from here:- https://getcomposer.org/
(1)Creating Laravel Project
composer create-project --prefer-dist laravel/laravel projectname
(2) For Starting Application
php artisan serve
After this you can access your application at: http://127.0.0.1:8000/
(3) Installing Builtin Authentication Library
php artisan ui vue --auth
(4) Syncing the Databases
php artisan migrate
(5) Making Controiller
php artisan make:controller Controllername
(6) Making Model
php artisan make:model Modelname
(7)Clearing Caches
For fast operations, laravel is having a feature to save your config, views and routes in its cache. so sometimes after making changes ,it wont make any effect in your system. may be laravel is picking it from cache folder, so use these commands to clear those configurations.
php artisan config:clear - For Clearing config Cache files
php artisan cache:clear - For Clearing entire cache folder
php artisan route:clear - For Clearing route Cache
php artisan view:clear - For Clearing view Cache
php artisan optimize - For Optimizing the application
3) DEFINING CONTROLLERS
In Laravel Controllers are placed in /app/Http/Controllers/ Folder.
In the top before declaring controller normally these namespaces we will be defining:-
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
For including additional helper files or models You can do like:-
use Illuminate\Support\Facades\Auth;
this is for including the Auth model
For Including a model defined in app folder named Cms.php.you can declare like:-
use App\Cms;
Declaring Controller will be like:-
class CmsController extends Controller
{
}
Define controller extending Controller class included through Name space.
4) DEFINING MODELS
Normally models are placed in app/ folder.
Before declaring model we have to include some namespaces like:-
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
The model will be declared like:-
class Cms extends Model
{
}
We declare class by extending Model class which is included through namespace.
When we use Eloquent ORM, we have to define certain properties in this file:-
protected $table = 'cms_pages';
Define the table name here
protected $primaryKey = 'page_id';
Define the tables's primary key with this
protected $guarded = [];
Normally Laravel needs to specify which fields are allowed for mass saving and all in the attribute protected $fillable. But if you declare $guarded variable to null, then all fields will be eligible for filling. If you want to restict certain features, you can define it in this variable separated by comma.
public $timestamps = false;
Normally while saving or creating, laravel will always check for fields named created_at and updated_at in databases. If you don't want those fields, just declare $timestamps as false.
5)Usage of Middlewares
In Laravel, they have given a provision to include middleware. I will explain a scenario where we can use it. Suppose we are logged in admin panel and we require every pages inside admin panel to check whether admin is logged in otherwise redirect to login page. So normally in other frameworks, we have to check whether the admin is logged in manually. But here we can do it very easy way using middleware.
For Authentication we have to first include
use Illuminate\Support\Facades\Auth;
before the controller declaration. Then in the constructor method, we can put
public function __construct()
{
$this->middleware('auth');
}
This will autocheck before calling each functions whether its setted or not. You can do this in routes also for each route calling.But more easier way is this one.
6) LOADING MODELS IN CONTROLLERS
For Loading models in controllers we have to first include it on top of controller page. Normally models are placed in app/ folder. so we can call it like:-
use App\Cms;
If we are writing models inside model folder in App directory, then:-
use App\Models\Cms;
Now we can call the model by just writing like this:-
$query=Cms::select('*');
$query->where('page_id','=','1')->get();
This is scenario where we calling direct query functions.
For calling functions defined in models:-
$cmsmodel = new Cms();
$cmsmodel->unpublish_record($id);
Here its calling unpublish_record function defined in cms model.
7)LOADING MODELS IN VIEWS
WE can call model functions in views by using this:-
$record= App\Cms::where('page_id',$records->parent)->first();
echo $record->title;
8) GET & POST METHODS ACCESSING
We can check, whether a form is submitted or a value is submitted using:-
if($request->has('submit')) {
}
For accessing posted values:-
$request->input('txtMenuTitle');
For getting this normally we have to include request parameter in function declaring.
public function store(Request $request)
{
}
And u have to include use Illuminate\Http\Request;
in the top of controller file.
9)VALIDATION IN LARAVEL
For validating form we can set rules like:-
$validatedData = $request->validate([
'txtMenuTitle' => 'required',
'txtParent' => 'required',
'txtTitle' => 'required',
'txtContent' => 'required',
]);
If the form doesn't fill all fields on submission, it will not execute further.
10)PAGINATION IN LARAVEL
For Laravel, we just have to call the paginate method by passing number of records per page. it will automatically do everything for you:-
For eg:-
$query=Cms::select('*');
$query->where('status','=','1');
if($keyword!=''){
$query->where('title', 'LIKE', "%{$keyword}%");
$query->orWhere('page_title','LIKE', "%{$keyword}%");
}
$records=$query->paginate(10);
Here am Just explaining a scenario case, suppose you want to paginate a list of pages, which will be having keywords search also. we will do like this.We have to pass number of records per page into paginate function.
In View you just have to put:-
<?php echo $pages->links();?>
So a pagination, which is styled in boostrap will appear.
11) LOADING VIEWS IN THE CONTROLLER FUNCTIONS
You can load views by calling:-
return view('cms.list', $data);
Here views are stored in resources/app/views folder
So by calling this laravel will pick list.blade.php file stored in cms folder inside views.
12) BLADE TEMPLATING IN LARAVEL
In Laravel view files will be saved as extensions blade.php. This is laravels own templating language.
i) For Loading css and js
All Css, js, images are stored in public folder. So inorder to access from it put like:-
<link rel="stylesheet" href="{{asset('theme')}}/assets/css/bootstrap.min.css" />
Here boostrap.min.css is stored in public/theme/assets/css folder.
You can use same to access all the css, js, image files stored in public folder.
2)For accessing Images stored in Uploads folder
<img src="{{ URL::to('/') }}/uploads/image.jpg" width="150px" height="150px" >
3) Extending a main layout in your view File
@extends('layouts.main')
Our Theme will be having a normal layout for some pages and its content part will be changing for most pages. so in this case we can define a main layout file in views folder and extend it in our view file. here the view is extending main.blade.php stored in layouts folder in the view folder.
4)Defining Sections in the layout Files
You can define sections in layout file and include it in the place you want it to appear. This is used when u want to include a common sidebar. but it have to appear between the dynamic view pages.
so define sections like:-
@section('content')
// Design code here
@endsection
then call yield to display where you want:-
@yield('content')
This you can put in the main layout file, so the section content will be replaced in it while including the same.
5) Including template file
You can also include a theme file into the template using the syntax:-
@include('layouts.messagebar')
Here the messagebar.blade.php defined in the layouts folder will be included.
13) IMAGE UPLOADING IN LARAVEL
There are many functions inbuilt in laravel for managing the image uploads.
if ($request->hasFile('txtFile') && $request->file('txtFile')->isValid()) {
//$request->hasFile('txtFile') -this function checks, whether the //file has been submitted from the form.
//$request->file('txtFile')->isValid()- this function checks, whether //the file submitted is valid.
//receiving file
$file = $request->file('txtFile');
//getting file values
$fileorgname = $file->getClientOriginalName();
$fileextension = $file->getClientOriginalExtension();
$filerealpath = $file->getRealPath();
$filesize = $file->getSize();
$filememetype = $file->getMimeType();
// defining allowed extensions
$allowedextensions=array('jpg','jpeg','png','bmp','gif');
//Checking whether uploaded file extension is matching the allowed extensions
if (in_array($fileextension,$allowedextensions))
{
// Getting the stored name and defining the path uploads in public folder to upload the file
$imagename = $request->txtFile->store('uploads');
$imagename=str_replace('uploads/','',$imagename);
$destinationPath = 'uploads';
//Storing the file to uploads folder
$file->move($destinationPath, $imagename);
}
}
14)CRUD OPERATIONS IN LARAVEL
INSERT
$insertdata = array('title'=>$name,'content'=>$content',banner'=>$imagename)
Cms::create($insertdata);
Here already CMs model has been loaded and by initiating Cms model and passing the array to create function, the data will be inserted.
UPDATE
ORM
$insertdata = array('title'=>$name,'content'=>$content',banner'=>$imagename)
Cms::where('page_id',$id)->update($insertdata);
Query Builder
DB::table('cms_pages')->where('page_id', $id)->update(['published' => 0]);
Here calling cms model and passing id and update array we can update records.
RETRIEVING
We can retrieve a single record or a group of records like this:-
ORM
$record= Cms::where('page_id',$id)->first();
QUERY Builder
For getting all:-
$rec= DB::table('cms_pages')->get();
For retrieving with condition:-
$rec=DB::table('cms_pages')->where('level', 1)->get();
DELETING
QUERY Builder Function
DB::table('cms_pages')->where('page_id', '=',$list[$i])->delete();
15) SESSIONS and FLASH Messages in Laravel
After saving data, if you want to show success or failure messages, the flash method in session will be handy.
we can set a flash variable in session like:-
$request->session()->flash('msg', 'Selected Items Deleted!!');
We can check, whether that msg variable is set by calling:-
if ($request->session()->has('msg')) {
}
For accessing the msg variable we can call like:-
$data['errormsg']=$request->session()->get('msg');
No comments:
Post a Comment