Laravel Notes
Laravel Notes
A) Blade::
- go to views and create a new file (master) : app.blade.php (here we will have
html5 full --)
<html>
<head>
<link rel = stylesheet href = https://www.getbootstrap.com/... >
</head>
<title> :: </title>
<body>
</body>
@stop
@section(footer)
@stop
B) Include css:
- inside master blade page:
Or
<href = {{ asset(/css/your_name.css) }}
@if (count($people))
@endforeach
</ul>
@endif
C) Environment:
have a look at .env and config folder once
we need not give the host name and db password in config
we can easily get it throught .env file and remember .env is ignored inside
.gitignore file
inside config/database.php u can easily choose the driver for your database
either mysql , postgresql , or sqlite
Choose the default one
Inside the .env file give the name of the database , username and the
password
D) Migration:
its like the version control for db
We need not extract the db and then send it to others ..
There are two methods up and down
Run existing migration: php artisan migrate (default given migration: users)
Eg. I want to change column user to username:
o First roll back : php artisan migrate:rollback
Schema::create('articles', function(Blueprint $table)
{
$table->increments('id');
$table->string('title');
$table->text('body');
$table->timestamps();
$table->timestamp('published_at');
});
E) Eloquent:
Select from table with variable value (SELECT FROM table with value
= kkjk)
o $article = App\Article::where(body ,this is my body)->get(); // I want
to get the result
o I get the collection with this
Controller:
php artisan make: controller ArticlesController plain
return $articles;
}
in the above case JSON returns all the parsed data so we want to
make it clean . Check this we will updating the same index function
inside the ArticlesController
View:
Inside Articles/index.blade.php
o First extend to master page
o Use the sections
o
@section('content')
<h1> Articles </h1>
<hr>
@foreach($articles as $article)
<article>
<h2> {{ $article->title }} </h2>
<div class = "body"> {{ $article->body }} </div>
</article>
@endforeach
@stop
@extends('app')
@section('content')
@stop
Route:
Route::get('articles/create' , 'ArticlesController@create');
Controller:
Service Providers:
o Go to config/app.php there is big list of service providers
o Add to list
'Illuminate\Html\HtmlServiceProvider',
Aliases:
o Scroll down to Aliases list :
o Aliases gives the sort of global way to access the namespaces
o Add new item for Form and HTML to last:
'Form' => 'Illuminate\Html\FormFacade',
'Html' => 'Illuminate\Html\HtmlFacade',
Form:
In the beginning the after opening the form we see that it sends request to
the same page:
<div class="form-group">
{!! Form::label('body' ,'Body:') !!}
{!! Form::textarea('body' , null , ['class' => 'form-control']) !!}
</div>
Posting data:
Since we are posting the data we need to now do something lets check it very
easy
Routes:
Route::post('articles' , 'ArticlesController@store'); //send post
req to articles page
But our form by default sends the req to current page, so we will have to change it
also:
Inside the ArticlesController we need a method to show the data passed by the
form:
use Request;
$articles = Article::latest()->get();
Delete this line from the controller because we need to give date and time
differently:
$input['published_at'] = Carbon::now();
This gives the date of which the article was published but we need time also. We
dont know this now. Accessors and mutators allows us to manipulate the data
before they are inserted into the database or after retrived.
Mutators:
Lets add a new method:
$this->atttributes['published_at'] =
Carbon::createFromFormat('Y-m-d' , $date);
Or
Carbon::parse('Y-m-d' , $date); //which can b used for future one , it wont
show the time
}
So after doing this what we can see is that the future posts also will be shown, we
assume that we keep future dates:
We need to get the articles where published_ at is less than or equal to current
now time.
Scope:
But still there is problem. Using this same long code for time and again is a problem
so we can use scope by which we can reduce our code. We take the query add
clause to it and use it in eloquent model.
Since I want the latest articles that have been published so I can do this as:
$articles = Article::latest('published_at')->published()->get();
We need a scope called published() , lets open our Model add new query scope.
Similarly the scope for the unpublished Articles can be fetched easily:
Dates:
Using carbon very easily we can play with the date and time. Inside the method
show. Since Carbon was used for created at this works.
dd($article->created_at);
dd($article->created_at->year);
dd($article->created_at->addDays(55));
dd($article->created_at->addDays(-4)->diffForHumans());
For the things that I saved manually we need to change it using Carbon.
For this just open the Model Articles.php and then add the method:
I) Validation:
Requests:
Since we save the data from the store() function inside the ArticlesController so we
need to make some changes in the same function. Currently even if we press the
save button so error message is shown on being empty.
We need to create a new Form request since we are working with Form. So run this.
There are two different methods at this class: Authorize and rules
Authorize means: do the users have permission to make such kinds of
requests. Ram cannot edit the comment made by Shyam.
Currently we dont have membership system so authorize() function returns
true for now.
Next we have rules:
public function rules()
{
return [
'title' => 'required|min:3',
'body' => 'required',
'published_at' => 'required|date'
];
}
After doing this what we can see is that before saving the data into database
firstly validation will take place
Understand the working cycle, from create.blade.php requests is passed for
creating form which comes to store function which again triggers to our
created request and checks if we can validate or not and then it checks the
parameters.
public function store(CreateArticleRequest $request)
{
//validation
Article::create(Request::all());
return redirect('articles');
}
@if ($errors->any())
<ul class="alert alert-danger">
@foreach($errors->all() as $error)
<li> {{ $error }}</li>
@endforeach
</ul>
@endif
Edit Article:
Create a new method (since route is already made by above list) in controller
public function edit($id)
{
$article = Article::findOrFail($id);
@section('content')
@include('errors.list')
@stop
You can see above , we use eloquent model for form , method is Patch , we
can easily use $article model which is passed from the controller to the view.
$article->update($request->all());
return redirect('articles');
}
Form Reuse:
In the above view u can see we have used method @include( ) which
includes the view ,
Copy the content of the form elements , apart from Form::openI() and close ,
and store it inside articles/form.blade.php
Change the submit button like this:
<div class="form-group">
{!! Form::submit($submitButtonText , ['class' => 'btn btn-primary form-
control']) !!}
</div>
And in our edit.blade.php
o @include('articles.form' , ['submitButtonText' => 'Update Article'])
o Meaning we update submitButtonText to Update Article
Same thing is to be applied for creating new article , only the form method
will be different
o @include('articles.form' , ['submitButtonText' => 'Add Article'])
Errors is saved to list.blade.php inside Errors folder
K) Eloquent Relationship:
One user can create many articles , and the articles is owned by the user.
There is a relationship between these two.
We have user model , add a new method there:
/**
* A user can have many articles
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function articles()
{
return $this->hasMany('App\Article');
}
But the problem with our create_article migration , we have not linked the
article with user , so we need to do this.
$table->integer('user_id')->unsigned();
Meaning unsigned() means the user_id cant be negative.
We also need to setup foreign constraint , if the user deletes their account ,
we want to delete all the things that the user own. (we want articles to be
deleted).
So we add a foreign key user_id , which references the id on users table and
on Deleting the account we cascade down the articles created by them. (on
the same above table)
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
K) Authentication System: