I added successfully a column to previous table using MySQL database dynamically - laravel

I added successfully a column to previous table using MySQL database dynamically, But when I fill up the form run and send it to the the database in my local server it shows:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'forge. posts' doesn't exist (SQL: select count(*) as aggregate from ` posts` where ` slug ` = hihello)
My code of migration table 'posts'
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('posts');
}
}
for inserting a new column called 'slug' in the 'post' table
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddSlugToUsers extends Migration
{
public function up(){
Schema::table('posts',function(Blueprint $table){
$table->string('slug')->unique()->after('title');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down(){
Schema::table('posts',function(Blueprint $table){
$table->dropColumn('slug');
});
}
}
Successfully inserted 'slug' column but problem is posting the form to the database.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Post;
use Session;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::orderBy('id', 'desc')->paginate(10);
return view('posts.index')->withPosts($posts);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('posts.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// validate the data
$this->validate($request, array(
'title' => 'required|max:255',
'slug'
=>'required|min:5|alpha_dash|min:5|max:255|unique:
posts, slug ',
'body' => 'required'));
// store in the database
$post = new Post;
$post->title = $request->title;
$post->slug = $request->title;
$post->body = $request->body;
$post->save();
Session::flash('success', 'The blog post was successfully
save!');
return redirect()->route('posts.show', $post->id);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$post = Post::find($id);
return view('posts.show')->withPost($post);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
// find the post in the database and save as a var
$post = Post::find($id);
// return the view and pass in the var we previously created
return view('posts.edit')->withPost($post);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
// Validate the data
$this->validate($request, array(
'title' => 'required|max:255',
'slug'=>'required|alpha_dash|min:5|max:255|unique:posts,slug',
'body' => 'required'
));
// Save the data to the database
$post = Post::find($id);
$post->title = $request->input('title');
$post->title=$request->input('slug');
$post->body = $request->input('body');
$post->save();
// set flash data with success message
Session::flash('success', 'This post was successfully saved.');
// redirect with flash data to posts.show
return redirect()->route('posts.show', $post->id);
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$post = Post::find($id);
$post->delete();
//for sesssion
Session::flash('success', 'The post was successfully deleted.');
return redirect()->route('posts.index');
}
}

'forge. posts' this looks like there is a space before table name posts. Did you check your model if there is a s

Related

How to check if many-to-many relation already exists in create and update

Every time I create a new book or update it with the same author, a new instance of the same author creates in DB
This is my codes here
Here is the BooksController
<?php
namespace App\Http\Controllers;
use App\Models\Author;
use App\Models\Book;
use Illuminate\Http\Request;
class BooksController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$books = Book::orderBy('created_at', 'desc')->with('authors')->paginate(5);
return view('books.index', [
'books' => $books
]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('books.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'author_name' => 'required',
'title' => 'required',
'release_year' => 'required|numeric',
'status' => 'required',
]);
I think I need to check here
// check if author already exists..
$authors = Author::all();
foreach($authors as $a){
if($a->name == $request->input('author_name')){
$author = $a;
}else{
}
}
Here if I have Glukhovski in the database and create a new book with the same author, another Glukhovski is added in the database, so I think there must be a way to check and if the author already exists, assign it to the book through the pivot table?
$author = Author::create([
'name' => $request->input('author_name')
]);
$book = Book::create([
'title' => $request->input('title'),
'release_year' => $request->input('release_year'),
'status' => $request->input('status')
]);
$book->authors()->attach($author->id);
return redirect('/books');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$book = Book::find($id);
return view('books.show')->with('book', $book);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$book = Book::find($id);
return view('books.edit')->with('book', $book);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$request->validate([
'author_name' => 'required',
'title' => 'required',
'release_year' => 'required',
'status' => 'required',
]);
... and here as well
// check if author already exists.....
//
$author = Author::create([
'name' => $request->input('author_name')
]);
$book = Book::find($id);
$book -> update([
'title' => $request->input('title'),
'release_year' => $request->input('release_year'),
'status' => $request->input('status')
]);
$book->authors()->sync($author->id);
return redirect('/books');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
Book::find($id)->delete();
return redirect('books');
}
}
Pivot table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAuthorBookTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('author_book', function (Blueprint $table) {
$table->id();
$table->foreignId('author_id');
$table->foreignId('book_id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('author_book');
}
}
you can check first for author in this way before you create the author, if author doesn't exist, it will create a new one
$author = Author::where('name',$request->input('author_name'))->first();
if(!$author){
$author = Author::create([
'name' => $request->input('author_name')
]);
}

Foreign Key not working in Laravel

I am creating cms app.
There are two tables - users and posts. Users table have an id of each user. On the other hand, Posts Table has user id which references to the id of users table.
However, while saving the post, I get an error that Field 'user_id' doesn't have a default value. Why is this? Please help me.
Posts Table:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->string('title');
$table->longText('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
DashboardController
<?php
namespace App\Http\Controllers\Dashboard;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Post;
class DashboardController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('dashboard.index');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('dashboard.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$post = new Post();
$post->title = $request->title;
$post->description = $request->description;
$post->save();
return redirect()->intended('dashboard');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
Post model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
//
}
User model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'fname', 'lname', 'email', 'password'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
}
Although, I defined a foreign key 'user_id', it doesn't automatically fetch the id from user table. How can I fix this?
You are not saving user_id:
public function store(Request $request)
{
$post = new Post();
$post->title = $request->title;
$post->description = $request->description;
$post->user_id = Auth::id();
$post->save();
return redirect()->intended('dashboard');
}
Firstly you need to add relations to Post.php:
public function user(){
return $this->belongsTo(User::class);
}
And in User.php:
public function posts(){
return $this->hasMany(Post::class);
}
In DashboardController in action store:
public function store(Request $request)
{
$post = new Post();
$post->title = $request->title;
$post->description = $request->description;
$user = Auth::user()->id;
$user->post()->save($post);
return redirect()->intended('dashboard');
}

SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value

I have created a new column in my database through a migration as below :
public function up(){
Schema::table('complains', function (Blueprint $table) {
$table->integer('user_id')->after('id');
});
}
When I fill in my form to post data into the database, I get the error below :
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into complains (title, body, name, regnumber, updated_at, created_at) values (Testing user id, Testing user id, John, cs-282-2145/2010, 2017-06-08 18:47:53, 2017-06-08 18:47:53))
How do I fix this?
I've had a similar issue with User registration today and I was getting a
SQLSTATE[HY000]: General error: 1364 Field 'password' doesn't have a default value (SQL: insert into users
I fixed it by adding password to my protected $fillable array and it worked
protected $fillable = [
'name',
'email',
'password',
];
I hope this helps.
Probably you aren't sending a value for user_id
Other possibility, yout can "transform" the column user_id nullable
Here is the code for my controller :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Complain;
use Illuminate\Support\Facades\Redirect;
use Session;
use Auth;
class ComplainController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('home');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, array(
'title' => 'required|max:255',
'body' => 'required'
));
$complain = new Complain;
$complain->user_id = Auth::user()->id;
$complain->title = $request->title;
$complain->body = $request->body;
$complain->save();
Session::flash('success', 'Your complain was sent to the operator, please wait for feedback.');
return redirect::back();
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$complain = Complain::find($id);
return view('admin')->withPost($complain);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
This is my model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Complain extends Model
{
}

ErrorException in SessionGuard.php | Getting error when trying to register user while creating new order

I want user to register and also buy a package. To do that I took input for registration details and package details. Now when I'm processing order to save package details in session and register, I get this error : Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of Illuminate\View\View given, called in C:\xampp\htdocs\rename\app\Traits\OrderRegister.php on line 63 and defined. I'm using an trait to register user and return back to function when registration is complete.
OrderController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Package;
use App\ListingType;
use Illuminate\Support\Facades\Auth;
use App\Order;
use Carbon\Carbon;
use App\Traits\OrderRegister;
class OrderController extends Controller
{
use OrderRegister;
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index($type)
{
$listingtype = ListingType::where('type', '=', $type)->first();
if ($listingtype) {
$packages = $listingtype->packages()->get();
return view('packages.index', compact('packages'));
}
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create($id)
{
$package = Package::where('id', '=', $id)->first();
if (Auth::check()) {
return view('order.create_loggedin', compact('package'));
}
else {
return view('order.create_register', compact('package'));
}
}
/**
* Process a new order request. Store order values in session.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function process(Request $request)
{
$order = ['package_id' => $request->package_id, 'order_qty' => $request->no_of_listing];
session(['order' => $order]);
if (Auth::guest()) {
return $this->register($request); // need to check session for orders available in OrderRegister trait.
}
return $this->store($request);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
if($request->session()->has('order')) {
$package = Package::where('id', '=', $request->package_id )->first();
if($request->user() == Auth::user()) {
for( $n=1;$n<=$request->no_of_listing;$n++) {
$order = new Order;
$order->package_id = $request->package_id;
$order->user_id = Auth::user()->id;
$order->expire_at = Carbon::now()->modify('+'.$package->duration_in_months.' months');
$order->save();
}
return redirect('/');
}
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
trait : OrderRegister.php
<?php
namespace App\Traits;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Validator;
trait OrderRegister
{
use RedirectsUsers;
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'username' => 'required|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'username' => $data['username'],
'password' => bcrypt($data['password']),
]);
$user->profile()->save(new UserProfile);
return $user;
}
/**
* Execute the job.
*
* #return void
*/
public function register(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
Auth::guard($this->getGuard())->login($this->create($request->all()));
return $this->store($request);
}
/**
* Get the guard to be used during registration.
*
* #return string|null
*/
protected function getGuard()
{
return property_exists($this, 'guard') ? $this->guard : null;
}
}
I could not find any solution for this error so created my own thread for the first time please someone help.
It throws an error because you are trying to login a vue.
in your OrderController.php you are using create method which return a view.
this method will override the create method on your trait.
So you have something like this :
Auth::guard($this->getGuard())->login(/* A view */);
you can at least rename the method on the trait from create to createUser for example.
then you call it from the guard like this :
Auth::guard($this->getGuard())->login($this->createUser($request->all()));

I can't get data when i am editing in laravel 5.1

i have address Book table and user table i am assigning
the many user in my address book while i am created everything is fine(ok)
but when i am editing every data back in my form without assign user .
how can i get the user in editing form ?? this is my Address Book Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\AddressRequest;
use App\Http\Requests;
use App\Models\Address;
use App\Models\User;
use App\Http\Controllers\Controller;`enter code here`
use Illuminate\Pagination\Paginator;
use Auth;
use DB;
use Session;
class AddressesController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index(Request $request)
{
Session::forget('searchaddress');
$addresses = Address::orderby('company_name');
$company_name = $request->input('company_name');
if(!empty($company_name)) {
//$addresses->where('company_name','LIKE','%'.$company_name.'%');
$addresses->where('company_name','LIKE','%'.$company_name.'%');
Session::set('searchaddress', $company_name);
}
$addresses = $addresses->paginate(5);
return view('address.index',compact('addresses'));
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
$users = User::lists('first_name','id');
return view('address.create',compact('users'));
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(AddressRequest $request)
{
$address = Address::create($request->all());
$firstname = Auth::user()->first_name;
$lastname = Auth::user()->last_name;
$address->created_by =$firstname." ".$lastname;
$address->users()->attach($request->input('user_list'));
$address->save();
return redirect('/addresses');
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
$address = Address::find($id);
return view('address.show',compact('address'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{ $users = User::lists('first_name','id');
$address = Address::findorFail($id);
return view('address.edit',compact('address','users'));
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update( AddressRequest $request ,$id)
{
$address = Address::findOrFail($id);
$address->update($request->all());
$address->users()->sync($request->input('user_list'));
return redirect('/addresses');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
$address = Address::find($id);
$address->delete();
return redirect('/addresses');
}
}
and that is my AddressBook Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Address extends Model
{
protected $fillable = [
'created_by',
'company_name',
'phone',
'email', 'address','comment'
];
public function users()
{
return $this->belongsToMany('App\Models\User')->withTimestamps();
}
public function getUserListAttribute()
{
return $this->users->lists('id');
}
}
[![enter image description here][1]][1]
[1]: http://i.stack.imgur.com/D4jXQ.png
You have belongsToMany relation, so in your edit action you also should get current Address users like this
public function edit($id)
{ $users = User::lists('first_name','id');
$address = Address::findorFail($id);
$address_users = $address->users->lists('id')->toArray();
return view('address.edit',compact('address','users', 'address_users'));
}
then in your view in select you should intersect arrays of $users and $address_users to get selected options.
{!! Form::select('user_list[], $users, isset($address_users) ? $address_users : null, ['id' => 'users_list', 'class' => 'form-control', 'multiple']) !!}
to avoid
isset($address_users) ? $address_users : null
you can define empty address_users array in your create method and do it like this
$address_users

Resources