Related
I have implemented an authentication system with NUXT framework and using laravel 9 Sanctum as the backend.
While logging in it works fine it update the store and everything is fine but while registering a user it gives a "Request failed with status code 419" "message": "CSRF token mismatch." errors:
this is my api.php file in laravel
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\TopicController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
//public routes
Route::post('register', [AuthController::class, 'reg']);
Route::post('login', [AuthController::class, 'login']);
Route::post('logout', [AuthController::class, 'logout']);
//protected routes by sanctum
Route::group(['middleware' => ['auth:sanctum']], function() {
Route::get('/user', function (Request $request) {
return $request->user();
});
});
This is my AuthController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Requests\UserRegisterRequest;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use Illuminate\Http\Respose;
use Illuminate\Auth\AuthenticationException;
use App\Http\Resources\User as UserResource;
class AuthController extends Controller
{
//register a user
public function reg(Request $request) {
$user_data = $request->validate([
'name' => 'required|string',
'email' => 'required|string|unique:users,email',
'password' => 'required|string|confirmed'
]);
$user = User::create([
'name' => $user_data['name'],
'email' => $user_data['email'],
'password' => bcrypt($user_data['password'])
]);
}
public function login(Request $request){
if($user = !auth()->attempt($request->only('email','password'))){
throw new AuthenticationException();
}
$token = auth()->user()->createToken('myapptoke')->plainTextToken;
return (new UserResource($request->user()))->additional([
'meta' => [
'token' => $token,
],
]);
}
//logout a user
public function logout(Request $request){
auth()->user()->tokens()->delete();
auth()->logout();
$response = [
'message' => 'logged out'
];
return $response;
}
}
Laravel .env file
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:D2F/NZpkDyj1hyCCzTKe3i/5khtp/WX1k17udQjv9R8=
APP_DEBUG=true
APP_URL=
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=backend-laravel-nine
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
SANCTUM_STATEFUL_DOMAINS=localhost:3000
SESSION_DOMAIN=localhost
This is my nuxt.config.js
export default {
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'NUXTfreshInstallation',
htmlAttrs: {
lang: 'en',
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' },
{ name: 'format-detection', content: 'telephone=no' },
],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
{rel:'stylesheet', href:'/css/bootstrap.min.css'}
],
scripts: [
{type:'text/javascript', serc:'/js/bootstrap.min.js'},
{type:'text/javascript', serc:'/js/bootstrap.bundle.min.js'},
]
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [],
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [ "./plugins/mixins/user.js", "./plugins/mixins/validation.js","./plugins/setErrorsPlugin.js"],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
'#nuxtjs/auth-next',
],
// router: {
// middleware: ["clearValidationErrors"]
// },
auth: {
strategies: {
laravelSanctum: {
provider: 'laravel/sanctum',
url: 'http://localhost:8000',
endpoints: {
login: {
url: '/api/login',
method: 'post',
//propertyName: 'meta.token'
},
user: {
url: '/api/user',
//method: 'get',
//propertyName: 'data'
},
logout: {
url: '/api/logout',
//method: 'post',
},
},
}
},
redirect: {
login: '/login',
logout: '/login',
home: '/'
}
},
// Axios module configuration: https://go.nuxtjs.dev/config-axios
axios: {
// Workaround to avoid enforcing hard-coded localhost:3000: https://github.com/nuxt-community/axios-module/issues/308
baseURL: 'http://localhost:8000',
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {},
}
This is the user register .vue page:
<template>
<div>
<div class="container col-md-6 mt-5">
<h2>Register</h2>
<hr>
<form #submit.prevent="register" method="post">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" placeholder="Enter Name" v-model="form.name" autofocus/>
<small class="form-text text-danger">Show errors</small>
</div>
<div class="form-group">
<label>Email address</label>
<input type="email" class="form-control" placeholder="Enter Email" v-model.trim="form.email" />
<small class="form-text text-danger">Show errors</small>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" v-model.trim="form.password" placeholder="Enter Password" />
<small class="form-text text-danger">Show errors</small>
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" class="form-control" v-model.trim="form.password_confirmation" placeholder="Enter Password Again" />
<small class="form-text text-danger">Show errors</small>
</div>
<button type="submit" class="btn btn-primary" >Register</button>
<p> Already have an account <nuxt-link to="/Login">Login </nuxt-link></p>
</form>
</div>
</div>
</template>
<script>
export default {
data () {
return {
form: {
name: '',
email: '',
password: '',
password_confirmation: '',
},
}
},
methods: {
async register (){
await this.$axios.post('/api/register', this.form);
await this.$auth.loginWith('laravelSanctum', {
data: {
email: this.form.email,
password: this.form.password
}
});
}
}
}
</script>
I have tried may troubleshooting techniques, I understood a little that the problem is in my .env file in "SANCTUM_STATEFUL_DOMAINS=localhost:3000 SESSION_DOMAIN=localhost "
if i add write it like this SANCTUM_STATEFUL_DOMAINS=localhost:3000,.localhost then the login does not work.
Is there any solutions I will appreciate your help Thanks
This is the error i get from the register request
Try to add csrf token into your registration view like this:
<form #submit.prevent="register" method="post">
#csrf
<div class="form-group">
<label>Name</label>
...
Try to change
SANCTUM_STATEFUL_DOMAINS=localhost:3000
to
SANCTUM_STATEFUL_DOMAINS=http://localhost:3000
I have been trying for 8 hours or so to get Inertia.js to work with Laravel and VueJS. What I get is a blank page with no error messages in the console (both the front-end and back-end consoles actually). What I have instead is a blank page and a tab with the loading animation running infinitely.
I searched on the Internet for an answer. I have found nothing that really helps.
What I'm trying to achieve is to get a result similar to the YouTube tutorial I'm using (https://www.youtube.com/watch?v=XEW2d2XHkAk).
Here is the content of the web.php file:
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
//
Route::get("/hello", function () {
return inertia("Hello");
});
Here is the content of the app.js file:
import Vue from 'vue'
import { createInertiaApp } from '#inertiajs/inertia-vue'
import { InertiaProgress } from '#inertiajs/progress'
InertiaProgress.init()
createInertiaApp({
resolve: name => require(`./Pages/${name}`),
setup({ el, App, props }) {
new Vue({
render: h => h(App, props),
}).$mount(el)
},
})
Here is the content of the Kernel.php file:
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\HandleInertiaRequests::class,
],
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}
Here is the content of the app.blade.php file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<link href="{{ mix('/css/app.css') }}" rel="stylesheet" />
<script src="{{ mix('/js/app.js') }}" defer></script>
</head>
<body>
#inertia
</body>
</html>
Here is the content of the Hello.vue file:
<template>
<div>hi there i am the hello page</div>
</template>
<script>
export default {};
</script>
OK. Someone I know found the answer.
So I was getting confused between these two commands:
npm run watch
versus
php artisan serve
The browser would open a tab with the app running on port 3000. So all I needed to do was to change the port in the browser. For example:
http://127.0.0.1:8000/hello
Edit: So to sum it all up, you use "npm run watch" to make sure your app is always up to date in the browser" and you run "php artisan serve" to serve your app to the browser. You run the two commands, but you have to use the port provided to you after running the "php artisan serve" command.
I have a laravel project which I have deployed on heroku. It opens when I submit the form it initially says " The information you’re about to submit is not secure " and if i still submit it, is says "419 page expired"
I tried a lot of solutions
my form sample is
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Upload File</title>
</head>
<body>
<!-- store route as action -->
<div class="container">
<div class="row">
<div class="col-12">
<br><br><br>
<form action="{{route('video')}}" method="post" enctype="multipart/form-data">
#csrf
{{ csrf_field() }}
<input type="file" class="form-control" name="videothing" id="videotitle" accept=" video/*">
<input type="submit" class="btn btn-sm btn-block btn-danger" value="Upload" onclick="spinner()">
</form>
#if (session('message'))
<h1 id="v">{{ session('message') }}</h1>
#endif
Laravel 419 Page Expired on production server. [ framework : Laravel | version : 7.5.2 ]
Laravel 6 Showed 419 | page expired
I followed these links and when I commented the
\App\Http\Middleware\VerifyCsrfToken::class,
in kernel.php, the error stops but on submitting the form it does not redirect to route rather just reloads the page,
I am sure it is CSRF issue but can't resolve it
In my VerifyCsrfToken.php, I did included
protected $except = [
//
'https://laraveluploading.herokuapp.com/',
'https://laraveluploading.herokuapp.com/video',
];
my session.php is
<?php
use Illuminate\Support\Str;
return [
'driver' => env('SESSION_DRIVER', 'file'),
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false,
'encrypt' => false,
'files' => storage_path('framework/sessions'),
'connection' => env('SESSION_CONNECTION', 'mysql'),
'table' => 'sessions','books','videos',
'store' => env('SESSION_STORE', null),
'lottery' => [2, 100],
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
'path' => '/',
'domain' => env('SESSION_DOMAIN', 'https://laraveluploading.herokuapp.com'),
'secure' => env('SESSION_SECURE_COOKIE',false),
'http_only' => true,
'same_site' => 'lax',
];
my web.php has
<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Exceptions\Handler;
use Symfony\Component\Debug\Exception\FatalThrowableError;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
})->name("start");
Route::post('/upload', function (Request $request) {
try{
if($request->file("thing")=="")
{
// return back()->withInput();
return redirect()->route('start')->with('message', 'Insert Data!');
}
else
{
$name=$request->file("thing")->getClientOriginalName();
$book=DB::table('books')->where('Title',$name)->count();
if($book>0)
{
return redirect()->route('start')->with('message', 'Document already exists!');
}
else{
$lang=$request->input("lang");
$cato=$request->input("catogory");
Storage::disk("google")->putFileAs("",$request->file("thing"),$name);
$url=Storage::disk('google')->url($name);
$details=Storage::disk("google")->getMetadata($name);
$path=$details['path'];
DB::insert('insert into books (Title, Catogory, Language, Url, FileId) values (?,?,?,?,?)', [$name,$cato,$lang,$url,$path]);
return redirect()->route('start')->with('message', 'Successfully uploaded document, you have recieved token!');
}
}
}
catch(Throwable $e)
{
return redirect()->route('start')->with('message', 'some error occured');
}
})->name("upload");
Route::get('/video', function(){
return view('showvideo');
})->name("startvideo");
Route::post('/video', function (Request $request) {
try{
if($request->file("videothing")=="")
{
// return back()->withInput();
return redirect()->route('startvideo')->with('message', 'Insert video!');
}
else
{
$videoname=$request->file("videothing")->getClientOriginalName();
$video=DB::table('videos')->where('video_name',$videoname)->count();
if($video>0)
{
return redirect()->route('startvideo')->with('message', 'Video name already exists!');
}
else{
// $lang=$request->input("lang");
// $cato=$request->input("catogory");
Storage::disk("google")->putFileAs("",$request->file("videothing"),$videoname);
$videourl=Storage::disk('google')->url($videoname);
// $videodetails=Storage::disk("google")->getMetadata($videoname);
// $path=$details['path'];
DB::insert('insert into videos (video_name, video_url) values (?,?)', [$videoname,$videourl]);
return redirect()->route('startvideo')->with('message', 'Successfully uploaded video');
}
}
}
catch(Throwable $e)
{
return redirect()->route('startvideo')->with('message', 'Some error occured in video uploading');
}
})->name("video");
in my application config var on heroku i have added the database credendtials (which is on azure) and also the google client id, secret key, refresh token required for connection with google drive.
I did tried my other solutions from different links but of no use.
Please help me resolve the issue.
I keep getting status 500 when 200 is expected. These are the files:
ExampleTest.php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* #return void
*/
public function testBasicTest()
{
$response = $this->get('/');
$response->assertStatus(200);
}
}
phpunit.xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./app</directory>
</whitelist>
</filter>
<php>
<env name="APP_ENV" value="testing"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="MAIL_DRIVER" value="array"/>
</php>
</phpunit>
This is the result returned
PHPUnit 7.4.0 by Sebastian Bergmann and contributors.
.F 2 / 2 (100%)
Time: 1.86 seconds, Memory: 20.00MB
There was 1 failure:
1) Tests\Feature\ExampleTest::testBasicTest
Expected status code 200 but received 500.
Failed asserting that false is true.
/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:133
/var/www/html/tests/Feature/ExampleTest.php:19
FAILURES!
Tests: 2, Assertions: 2, Failures: 1.
This is the Laravel log file
[2018-10-15 20:56:09] testing.ERROR: Call to a member function load() on null (View: /var/www/html/resources/views/app.blade.php) {"exception":"[object] (ErrorException(code: 0): Call to a member function load() on null (View: /var/www/html/resources/views/app.blade.php) at /var/www/html/app/Ezybyz/Configuration/ProvidesScriptVariables.php:46, Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Call to a member function load() on null at /var/www/html/app/Ezybyz/Configuration/ProvidesScriptVariables.php:46)
app.blade.php
#php
$config = array_merge(
Ezybyz::scriptVariables(), [
// Add key and value here if you want to added to initial state
]
)
#endphp
#extends('layouts.main')
#push('meta')
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
<meta name="csrf-token" content="{{ csrf_token() }}">
{{-- Fix for chunk error in Webpack and Vue-Router --}}
<base href="/" />
#endpush
#push('favicon')
<link rel="shortcut icon" href="{{ asset('favicon.ico?v=2') }}" type="image/x-icon" />
#endpush
#push('css')
<link rel="stylesheet" href="{{ mix('css/app.css') }}">
#endpush
#push('header_js')
{{-- EzyByz initial state provider --}}
<script>
window.App = #json($config)
</script>
{{-- Add whitelisted routes for making API calls --}}
#routes
#endpush
#push('title')
<title>{{ config('app.name') }} </title>
#endpush
#section('content')
<div id="app" v-cloak>
<app />
</div>
#endsection
#push('footer_js')
#if(config('echo.realtime'))
{{-- Load socket.io --}}
<script src="//{{ Request::getHost() }}:6001/socket.io/socket.io.js" defer></script>
#endif
<script src="{{ mix('js/manifest.js') }}" defer></script>
<script src="{{ mix('js/vendor.js') }}" defer></script>
<script src="{{ mix('js/app.js') }}" defer></script>
#endpush
ProvidesScriptVariables.php
<?php
namespace App\Ezybyz\Configuration;
use App\Ezybyz\Ezybyz;
use Illuminate\Support\Facades\Auth;
use App\Ezybyz\Contracts\InitialFrontendState;
trait ProvidesScriptVariables
{
/**
* Get the default JavaScript variables for Spark.
*
* #return array
*/
public static function scriptVariables()
{
return [
'csrfToken' => csrf_token(),
'env' => config('app.env'),
'api_endpoint' => config('ezybyz.app.api'),
'sponsor' => self::getSponsor(),
];
}
protected static function getState()
{
return Ezybyz::call(InitialFrontendState::class . '#forUser', [Auth::user()]);
}
protected static function getSponsor()
{
if ($link = request()->referrallink) {
$user = Ezybyz::user()->find($link->user_id);
return [
'user_id' => $user->id,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->email,
'profile' => $user->profile,
];
}
// We Will Return a Default Sponsor
else {
$user = Ezybyz::user()->first()->load('profile');
return [
'user_id' => $user->id,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->email,
'profile' => $user->profile,
];
}
}
}
Any help is greatly appreciated.
Try to use RefreshDatabase trait in the test class:
use Illuminate\Foundation\Testing\RefreshDatabase;
class ExampleTest extends TestCase
{
use RefreshDatabase;
public function testBasicTest()
{
$response = $this->get('/');
$response->assertStatus(200);
}
}
add $this->withoutExceptionHandling(); before $response = $this->get('/'); to get more information about the error.
One possible cause of this error message is, you don't have the openssl
php
extension enabled.
just edit your class to return true
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* #return void
*/
public function testBasicTest()
{
$this->assertTrue(true);
}
}
then run test in your command
vendor/bin/phpunit
Do check with your routes. Check if you have provided 'name' to your base route.
eg:
In routes/web.php, Do the following:
Route::get('home','BlogController#home')->name('home');
Now go to the test case and do replace the following code:
$response = $this->get('home');
Let me know if it works for you.
In my controller I have added this code.For different view files there are different functions.How can I add meta tags for different function for different views?
This is my controller:
<?php
class home extends CI_Controller {
function index()
{
$data['meta_title'] = 'Tracenow | iOS Version';
$data['meta_description'] = 'Responsive HTML5 Theme in iOS Style';
$data['meta_keywords'] = 'responsive html5 theme, ios, android, material design, landing, application, mobile, blog, portfolio, bootstrap 3, css, jquery, flat, modern';
$data['meta_author'] = '8Guild';
$data['meta_viewport'] = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';
$this->load->view('home_page/home_page');
}
function about()
{
$this->load->view('home_page/about');
}
function blog()
{
$this->load->view('home_page/blog');
}
function blog_single()
{
$this->load->view('home_page/blog-single');
}
}
?>
For this you can simply use this in your controller:
$data['meta_title'] = 'Your meta title';
$data['meta_description'] = 'Your meta description';
$data['meta_keywords'] = 'Your meta keywords';
And you view should be like:
<title><?php echo $meta_title; ?></title>
<meta name="description" content="<?php echo $meta_description; ?>" />
<meta name="keywords" content="<?php echo $meta_keywords; ?>" />
Hopefully it will help you. or if you need any help please comment below.
You can use this library
Meta Tags
On your Controller
$data['metas'] = array(
array('name'=>'description', 'content'=>'A short but sweet DEFAULT description of this fine site'),
array('name' =>'keywords', 'content'=>'some awesome DEFAULT keywords for those rascally web crawlers')
);
On your View
<?php
foreach($metas as $meta)
{?>
<meta name="<?=$meta['name']?>" content="<?=$meta['content']?>" />
<?php }?>
class Home extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->helper('html'); //Load global helper 'html'
}
[...]
//in controller: meta tag
$meta = array(
array(
'name' => 'robots',
'content' => 'no-cache'
),
array(
'name' => 'description',
'content' => 'My Great Site'
),
array(
'name' => 'keywords',
'content' => 'love, passion, intrigue, deception'
),
array(
'name' => 'robots',
'content' => 'no-cache'
),
array(
'name' => 'Content-type',
'content' => 'text/html; charset=utf-8', 'type' => 'equiv'
)
);
//HTML
<!DOCTYPE html>
<head>
<title></title>
<?= meta($meta) ?> //use helper HTML to show meta tag
</head>
// Generates:
// <meta name="robots" content="no-cache" />
// <meta name="description" content="My Great Site" />
// <meta name="keywords" content="love, passion, intrigue, deception" />
// <meta name="robots" content="no-cache" />
// <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
Font:https://codeigniter.com/userguide3/helpers/html_helper.html?highlight=helper
In your controller :
$this->output->set_common_meta($page_title, $page_description, $page_keywords); // for title, description, keywords
$this->output->set_meta('property_name', 'property_value'); // for other properties