Laravel php artisan migrate command not working - laravel-5

i have install laravel 5.4 and trys to migrate a table.but migrate is not working.there is no errors showing.i have edited my env file correctly and also databse.php. what can be the reason?
my env
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=8000
DB_DATABASE=vim
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
migration script
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}

Related

CSRF token mismatch in NUXT Axios requests but the NUXT Auth is working perfectly fine

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

Laravel sanctum - unathenticated after refresh. Why am I being unauthenticated?

I have a simple authentication system in which I use vue to handle frontend and Laravel to handle the backend. Laravel Sanctum is being used to authentication.
When I login, it works fine and within Laravel I can dump the logged in user fine.
however when i refresh the page I am no longer authenticated.
As you can see I'll be using app.blade.php to tell javascript who the logged in user is, but isLoggedin is always false.This seems wrong to me. Am I missing something?
Any help is appricated.
api.php
Route::post('login', [UserController::class, 'login']);
UsersController#login
public function login(Request $request)
{
$credentials = [
'email' => $request->email,
'password' => $request->password,
];
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
$success = true;
$message = 'User login successfully';
$user = auth()->user();
} else {
$success = false;
$message = 'Unauthorised';
$user = null;
}
// response
$response = [
'success' => $success,
'message' => $message,
'user' => $user
];
return response()->json($response);
}
.env
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DRIVER=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=cookie
SANCTUM_STATEFUL_DOMAIN=localhost
SESSION_DOMAIN=localhost
SESSION_LIFETIME=120
SESSION_SECURE_COOKIE=false;
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}"
app.blade.php
<!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" value="{{ csrf_token() }}"/>
<title>{{env('APP_NAME')}}</title>
<link href="{{ mix('css/app.css') }}" type="text/css" rel="stylesheet"/>
</head>
<body>
#if (Auth::check())
#php
$user_auth_data = [
'isLoggedin' => true,
'user' => Auth::user()
];
#endphp
#else
#php
$user_auth_data = [
'isLoggedin' => false
];
#endphp
#endif
<script>
window.Laravel = JSON.parse(atob('{{ base64_encode(json_encode($user_auth_data)) }}'));
console.log(window.Laravel);
</script>
<div id="app">
</div>
<script src="{{ mix('js/app.js') }}" type="text/javascript"></script>
</body>
</html>```
Fixed it.
Change SANCTUM_STATEFUL_DOMAIN=localhost
To: SANCTUM_STATEFUL_DOMAINS=localhost:9192
You need the port number.

How to open link when add new group? laravel

I have two records.
When I click on +. Must open the desired group. But I see it that way. That is, it opens both groups.
slider_gorups table
Schema::create('slider_groups', function (Blueprint $table) {
$table->id();
$table->string('title')->nullable();
$table->timestamps();
});
sliders table
Schema::create('sliders', function (Blueprint $table) {
$table->id();
$table->foreignId('userId')->constrained('users')->cascadeOnDelete();
$table->unsignedBigInteger('groupId')->nullable();
$table->string('src')->nullable();
$table->timestamps();
});
groups.blade.php
<a href="{{ route('admin::sliders.index', $sliderGroup->id) }}" class="mr-1">
<i class="la la-plus text-grey text-shadow-custom font-medium-4 font-weight-normal"></i>
</a>
web.php
Route::resource('slider-groups', 'Admin\SliderGroupController');
Route::prefix('slider-groups/{sliderGroupId}')->group(function(){
Route::resource('sliders', 'Admin\SliderController');
});
put your groups code
i think problem is in their id attribute
each group must has its own id and same with its own "+" id!
in this case when you click on "+", it will open group with same id

create authentication laravel 5

I have these 2 tables with many to many relationship connected using a junction table. The idea is that I can get the user data to make the user an author in a journal data and it works so far.
User table :
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->integer('phone')->nullable();
$table->string('address')->nullable();
$table->string('password');
$table->rememberToken();
$table->enum('level', ['admin', 'author']);
$table->timestamps();
});
}
Journal table :
public function up()
{
Schema::create('journal', function (Blueprint $table) {
$table->increments('id');
$table->string('title', 255);
$table->text('abstract');
$table->text('file');
$table->integer('id_edition')->unsigned();
$table->timestamps();
});
}
Junction table :
public function up()
{
Schema::create('penulis', function (Blueprint $table) {
// Create tabel penulis
$table->integer('id_user')->unsigned()->index();
$table->integer('id_journal')->unsigned()->index();
$table->timestamps();
// Set PK
$table->primary(['id_user', 'id_journal']);
// Set FK penulis --- user
$table->foreign('id_user')
->references('id')
->on('users')
->onDelete('cascade')
->onUpdate('cascade');
// Set FK penulis --- journal
$table->foreign('id_journal')
->references('id')
->on('journal')
->onDelete('cascade')
->onUpdate('cascade');
});
}
Now I have this view that shows journals data along with the buttons to edit or delete it. What I want to make is that only the user that are entitled as the author of the journal that has the capacity to access these buttons. How do I make it ? below is the view code :
<tbody>
<?php foreach ($journal_list as $journal): ?>
<tr>
<td style="">{{ $journal->title }}</td>
#if (Auth::check())
<td style="width: 130px; overflow: hidden;">
<div class="box-button">
{{ link_to('journal/' . $journal->id . '/edit?edition=' . $edition->id, 'Edit', ['class' => 'btn btn-warning btn-sm']) }}
</div>
<div class="box-button">
{!! Form::open(['method' => 'DELETE', 'action' => ['JournalController#destroy', $journal->id]]) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-danger btn-sm']) !!}
{!! Form::close() !!}
</div>
</td>
#endif
</tr>
<?php endforeach ?>
</tbody>
Sorry for my bad English and if my question is stupid. Thanks!
You need to use a combination of middleware and Gate facade.
Generate a policy
Write a policy
Like this:
public function edit-journal(User $user, Journal $journal)
{
return $user->id === $journal->user_id;
}
public function delete-journal(User $user, Journal $journal)
{
return $user->id === $journal->user_id;
}
3. You can now use the Gate facade with blade
Like this:
#can('edit-journal', $journal)
<div class="box-button">
{{ link_to('journal/' . $journal->id . '/edit?edition=' . $edition->id, 'Edit', ['class' => 'btn btn-warning btn-sm']) }}
</div>
#endcan
#can('delete-journal', $journal)
<div class="box-button">
{!! Form::open(['method' => 'DELETE', 'action' => ['JournalController#destroy', $journal->id]]) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-danger btn-sm']) !!}
{!! Form::close() !!}
</div>
#endcan
You will have to register a middleware for your edit and delete route. Your routes should look like:
//Routes
Route::get('journal/' . {$journal_id} . '/edit', ['as'=>'editJournal','middleware' => 'journal:edit', 'uses'=>'JournalController#edit']
//You need to change your delete form so the action points to that route
Route::delete('journal/' . {$journal_id}, ['as'=>'deleteJournal','middleware' => 'journal:delete', 'uses'=>'JournalController#destroy']
In your middleware, you should have something like:
//Journal Middleware
public function handle($request, Closure $next, $role)
{
$parameters = $request->route()->parameters();
$journal = Journal::findOrFail($parameters['journal_id']);
if (Gate::allows($role.'-journal', $journal)) {
return $next($request);
}else{
abort(403, "You do not have the permission to ".$role." this journal")
}
}
What I;ve done in similar cases is to add a function inside the model that you want to check with all the logic. So for example in your case would be something like:
/Model/Journal.php
public function canBeModifiedByUser($user_id){
//Check all the things that you want
}
Then in the view you can do something like:
if($journal->canBeModifiedByUser($journal->user->id))
Also I would suggest you to check some ACL packages, it might be an overkill for you atm but it might just be what you need.
I would suggest using gates
in your auth service provider you can do
$gate->define('can-modifiy', function ($user) {
// whatever code you want to determine if the user can eg
return $user->hasRole('admin');
});
then in your views you can use #can
#can ('can-modify')
<button>delete</button>
#endcan
This can also be used in your controllers with
$this->authorize('can-modify');
or
Gate::allows('can-modify');
This is in the docs at https://laravel.com/docs/5.3/authorization#writing-gates

How to retrieve data from a form ( type = "text" ) and store in database in laravel 5.2

I want to retrieve data for a user's comment using a form but I'm not too sure how to do that even after looking at the laravel documentation and videos.
my "CommentsController" code snipit looks like this
public function submitComment(Request $request){
$this->validate($request, [
'comment'=> 'required|max:500'
]);
$comment= new Comments;
$comment->comments=$request->input->('comment');
DB::table('comments')->insert(
array('user_id'=>1,
'post_id'=>1,
'comment'=> $comment)
);
, my form snipit looks like this
<?php
echo '<form method="POST" action="comments"> ';
echo '<input name="comment" type="text" cols="40" rows="5" style="width:200px; height:50px;" placeholder="Type Here">';
echo '<input type="submit">' ;
echo '</form>';
?>
and my table in the database looks like this
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('post_id')->unsigned();
$table->string('comments');
$table->timestamps();
//Foreign Keys
$table->foreign('post_id')
->references('id')->on('posts')
->onDelete('cascade');
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
});
Try changing
$comment->comments=$request->input->('comment');
to
$comment->comments =$request->comment;
Basically you can get a input by $request->formName
I also tent to create new records like
$record = Comment::create([ 'user_id' => $userId, 'post_id' => $postId, 'comments' => $request->comments]);
But you would need to create a model to do so like that.
php artisan make:model Comment

Resources