Cannot insert data in laravel - php

I'm new to laravel, i want to insert data in Laravel for that i have written following code but the data is not inserted in the database and there is no error coming. My code is as follows, i have Created model, view, controller for that.
Controller : Category.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Model\Category;
class Categories extends Controller
{
public function create()
{
return view('pages.addCategories');
}
public function store(Request $request)
{
$validatedData = $request->validate([
'name' => 'required',
]);
Category::create($request->all());
return redirect('admin/categories');
}
}
categories_table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->unsignedInteger('parent_id')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
}
View:
<form action="/admin/add-categories" method="post" role="form">
{{ csrf_field() }}
<div class="card-body">
<div class="form-group">
<label for="exampleInputEmail1">Category Name</label>
<input type="text" class="form-control" name="name" placeholder="Enter Category">
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
Model Category :
<?php
namespace App;
namespace App\Model;
use DB;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = [
'name'
];
public function subcategory(){
return $this->hasMany('App\Category', 'parent_id');
}
}
web.php
Route::get('admin/categories', 'Categories#create');
Route::post('admin/add-categories', 'Categories#store');

In your Category model you can have one namespace only.
So if the file is within app\Model\ then use this only:
namespace App\Model;
and remove
namespace App;
Then in the controller you can do this instead:
$validatedData = $request->validate([
'name' => 'required',
]);
Category::create($validatedData);

Related

Illuminate\Contracts\Container\BindingResolutionException Target class [App\Http\Controllers\FileController\FileController] does not exist

This is my web.php file and i have used the correct get and post methods and have specified the path correctly
<?php
use Illuminate\Support\Facades\Route;
namespace App\Http\Controllers\FileController;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::post('store', [FileController::class,'store']);
Route::view('imgupload','imageUpload');
blade file--imageUplods;where i get like 2 images and store it as a multiple entry in the db
<form method="post" action="store" enctype="multipart/form-data">
#csrf
<div class="input-group realprocode control-group lst increment" >
<input type="file" name="filenames" class="myfrm form-control" id="filenames">
<div class="input-group-btn">
<button class="btn btn-success" type="button"> <i class="fldemo glyphicon glyphicon-plus">
</i>Add</button>
</div>
</div>
<div class="clone hide">
<div class="realprocode control-group lst input-group"
style="margin-top:10px">
<input type="file" name="filenames" class="myfrm form-control"
id="filenames">
<div class="input-group-btn">
<button class="btn btn-danger" type="button"><i class="fldemo
glyphicon glyphicon-remove">
</i> Remove</button>
</div>
</div>
</div>
<button type="submit" class="btn btn-success" style="margin-
top:10px">Submit</button>
</form>
</div>
model: filemodel - filesnames is the only attribute to enter
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class file extends Model
{
use HasFactory;
protected $fillable = [
'filenames'
];
public function setFilenamesAttribute($value)
{
$this->attributes['filenames'] = json_encode($value);
}
}
Controller-FileController- imageUploder is the blade file
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Models\File;
use Illuminate\Support\Facades\Auth;
class FileController extends Controller
{
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('imageUpload');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'filenames' => 'required',
'filenames.*' => 'image'
]);
$files = [];
if($request->hasfile('filenames'))
{
foreach($request->file('filenames') as $file)
{
$name = time().rand(1,100).'.'.$file->extension();
$file->move(public_path('files'), $name);
$files[] = $name;
}
}
$file= new File();
$file->filenames = $files;
$file->save();
return redirect('imageUpload')->with('success', 'Your images has
been successfully added');
}
}
You are mixing up 'use' and 'namespace'. 'namespace' is for defining the namespace of the current class
Change this line
namespace App\Http\Controllers\FileController;
to
use App\Http\Controllers\FileController;
Change what Gert said about the namespace in web.php
Change
class file extends Model
to
class File extends Model

Problem with inserting from input in database

I have many to many relationship between UserProfile model and UserTv model. Here are the tables.
user_profiles
id user_id username
1 1 AuthUser
tv
id name
1 Action
2 Drama
3 Comedy
4 manually added some genre from input from authenticated user
user_tv
id user_id tv_id
1 1 2
1 1 4
For example, these first three ids in tv table (Action, Drama, Comedy) are inserted through seeders and this fourth id is inserted manually through input text from form by that user who is authenticated. And there lies the my problem. I want that those values that are manually added through input in form to only be able to see that user that inserted those values, and all other users can't. But also I want all users to remain to see those first three values that are generated through seeder. Currently everything works so that all users can see everything. Any help is appreciated. Here is my code.
UserProfile.php
<?php
namespace App;
use App\User;
use Illuminate\Support\Facades\App;
use Illuminate\Database\Eloquent\Model;
class UserProfile extends Model
{
protected $fillable = [
'user_id',
'username',
];
public function user()
{
return $this->belongsTo(User::class);
}
public function tvs()
{
return $this->belongsToMany(UserTv::class, 'user_tv', 'user_id', 'tv_id');
}
}
UserTv.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserTv extends Model
{
protected $table = 'tv';
protected $fillable = [
'name'
];
public function userProfiles()
{
return $this->belongsToMany(UserProfile::class, 'user_tv', 'tv_id', 'user_id');
}
}
web.php
Route::get('profile/{profile}', 'UserProfileController#showProfile')->name('profile.show');
Route::patch('profile/update-tv-options', 'TvController#updateTvOptions')->name('profile.update.tv.options');
Route::post('profile/insert-tv-options', 'TvController#insertTvOptions')->name('profile.insert.tv.options');
TvController.php
<?php
namespace App\Http\Controllers;
use App\UserTv;
use App\UserProfile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\InsertTvOptionsRequest;
use App\Http\Requests\UpdateTvOptionsRequest;
class TvController extends Controller
{
public function updateTvOptions(UpdateTvOptionsRequest $request)
{
$user = Auth::user();
$userProfile = UserProfile::where('user_id', Auth::id())->first();
$userProfile->update($request->all());
$data = $request->get('tvsOptions', '[]');
$userProfile->tvs()->sync($data);
return redirect()->route('profile.show', [$user->username]);
}
public function insertTvOptions(InsertTvOptionsRequest $request)
{
$user = Auth::user();
$tv = UserTv::create($request->all());
return redirect()->route('profile.show', [$user->username]);
}
}
UserProfileController.php
<?php
namespace App\Http\Controllers;
use App\User;
use App\UserTv;
use App\UserProfile;
class UserProfileController extends Controller
{
public function showProfile($username, Request $request)
{
$profileId = User::getIdFromUsername($username);
$userForShowProfile = User::with('userProfile')->where('id', $profileId)->firstOrFail();
$tvsOptions = UserTv::get();
$userTvsOptions = UserProfile::findOrFail($profileId)->tvs()->get();
return view('profile.show', compact('userForShowProfile', 'tvsOptions', 'userTvsOptions'));
}
}
show.blade.php
<section data-edit="movies" class="editMovies">
<h3 class="textBold">Film</h3>
<form action="{{ route('profile.update.tv.options') }}" method="POST" class="flex">
#method('PATCH')
#csrf
<div class="form-group flex">
#isset($tvsOptions, $userTvsOptions)
#foreach($tvsOptions as $option)
<div class="interestedIn">
<input type="checkbox" name="tvsOptions[]" value="{{ $option->id }}" {{ $userTvsOptions->contains('id', $option->id)? 'checked': ''}}>
<label for="">{{ $option->name }}</label>
</div>
#endforeach
#endisset
</div>
<div class="form-group">
<label for="" class="textBold">Button FOR CHECKBOX</label>
<input type="submit" class="form-control" name="submit" value="BUTTON">
</div>
</form>
<form action="{{ route('profile.insert.tv.options') }}" method="POST" class="flex">
#csrf
<div class="form-group mt-5">
<input type="text" name="name" placeholder="INSERT NEW MOVIE GENRE">
</div>
<div class="form-group">
<label for="" class="textBold">Button FOR INSERT!!!</label>
<input type="submit" class="form-control" name="submit" value="BUTTON">
</div>
</form>
</section>
And I want to contain first three options for all users and that fourth option for only this user that inserted that.
Something like this?
$defaultTvsOptions = UserTv::whereIn('name', ['Action', 'Drama', 'Comedy'])->get(); // return only action, drama and comedy. you can use ids.
$userTvsOptions = UserProfile::findOrFail($profileId)->tvs;
$tvsOptions = $defaultTvsOptions->merge($userTvsOptions); // merge default and logged user tvs options
To make it more maintainable, you could use configs in your root directory of project.
$defaultTvsOptions = UserTv::whereIn('name', config('config name where return the array'));
Hope it helps you.
Hey As you Have a pivot table You can pull the data Like This:
Userprofile model
public function tv() {
return $this->hasManyThrough(
'Tv class ',
'user_tv class',
'user_id',
'id',
'user_id',
'tv_id'
);
}
UserController
$data = UserProfile::with('tv')
->where(condition)
->get();

Laravel: Error trying to get unique users to create posts

Right so im trying to make a website where a registered user can create a post. The issue i am having rigt now is getting the post to be added to the the database. It should work but im getting an error.
The error:
Call to a member function posts() on null
The error points to my post controller class
<?php
use App\Post;
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class postController extends Controller
{
public function postCreatePost(Request $request){
$post = new Post();
$post->body = $request['body'];
$request->user()->posts($post); //points here
return redirect()->route('dashboard');
}
}
This is my post migration up method:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->text('body');
$table->integer('user_id');
});
}
Post model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function user(){
return $this->belongsTo['App\User'];
}
}
User model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable;
class User extends Model implements Authenticatable
{
use \Illuminate\Auth\Authenticatable;
public function posts(){
return $this->hasMany('App\Post');
}
}
The section the user types in:
<section class="row new-post">
<div class="col-md-6 col-md-offset-3">
<form action="{{ route('postcreate') }}" method="post">
<div class="form-group">
<textarea class="form-control" name="body" rows="5" placeholder="your post"></textarea>
</div>
<button type="submit" class="btn btn-primary">Create post</button>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
</div>
</section>
The problem is that on your controller you do:
$request->user()->posts($post); //points here
You are considering that user() will always return something.
If your route isn't guarded by the auth middleware, $request->user() may return null if there's no authenticated user.
So you have two options: Or you add the auth middleware, or you put an if on your code:
if ($request->user()) {
$request->user()->posts($post);
}
However, this will fix the error but it won't create a post
public function postCreatePost(Request $request){
$post = new Post();
$post->body = $request['body'];
$request->user()->posts($post); // This call isn't valid.
return redirect()->route('dashboard');
}
The right way to do is:
public function postCreatePost(Request $request){
$request->user()->posts()->create([
'body' => $request->body
// Here I'm assumming that the only field is the `body`,
// but you may need other fields if they exists.
// the `user_id` field will be automatically filled.
];
return redirect()->route('dashboard');
}

Save a File To mysql Database From a form using laravel

Good day Everyone, I'm less than 1 week old in laravel. I'm trying to save a Register CV page to MySQL database. Although my Form contains an upload file. While saving it to the database only the name of the file is saved the file itself isnt there.
My code goes thus.
RegisterController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\candidate;
use App\Http\Requests;
class RegisterController extends Controller
{
public function register(Request $request) {
$this->validate($request, [
'surname' => 'required',
'other_name' => 'required',
'email' => 'required',
'phone' => 'required',
'gender' => 'required',
'field' => 'required',
'qualification' => 'required',
'resume' => 'required'
]);
$candidates = new Candidate;
$candidates->surname = $request->input('surname');
$candidates->other_name = $request->input('other_name');
$candidates->email = $request->input('email');
$candidates->phone = $request->input('phone');
$candidates->gender = $request->input('gender');
$candidates->field = $request->input('field');
$candidates->qualification = $request->input('qualification');
$candidates->resume = $request->input('resume');
$candidates->save();
return redirect('/career')->with('response', 'Registered Successfully');
}
}
2018_03_28_152114_create_candidates_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCandidatesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('candidates', function (Blueprint $table) {
$table->increments('id');
$table->string('surname');
$table->string('other_name');
$table->string('email');
$table->string('phone');
$table->string('gender');
$table->string('field');
$table->string('qualification');
$table->string('resume');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('candidates');
}
}
then the form
<form class="form-horizontal pv-20" action="/career/test-apply" method="POST" role="form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
.........
........
<div class="form-group">
<label class="col-sm-2" for="resume">Upload Resume</label>
<div class="col-sm-10">
<input class="form-control" type="file" name="resume" id="resume" accept="application/pdf">
</div>
</div>
<div class="form-group">
<label class="col-sm-6" for="resume"></label>
<div class="col-sm-6">
<button type="submit" class="btn btn-default btn-curve btn-animated pull-right">Submit <i class="fa fa-play"></i></button>
</div>
</div>
</form>
You can save the file in the Public directory of your project. Then, you can just save the name of the file in MySQL database.

Laravel 5.3 throw MethodNotAllowedHttpException on Store using restfull controller

I am trying to add a record to a database utilizing a resource controller, however, I'm getting MethodNotAllowedHttpException error. I'm using a pivot table. I have gone through several similar questions like a link! but none seem to answer me. This is my code:
Routes.php
Route::group(['prefix' => 'user'], function () {
Route::resource('categories', 'User\CategoriesController');
});
CategoriesController.php
<?php
namespace App\Http\Controllers\User;
use Session;
use Sentinel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Sections;
use App\Models\Categories;
use App\Models\Users;
use App\Models\CategorieUser;
class CategoriesController extends Controller
{
public function __construct()
{
$this->middleware('sentinel.auth');
}
public function index()
{
$categories = Categories::all();
return view('user.categories.index', ['categories' => $categories]);
}
public function create()
{
$sections = sections::all();
return view('user.categories.create', ['sections' => $sections]);
}
public function store(Request $request)
{
// records in table categories
$categories = new Categories();
$categories->name = $request->name;
$categories->sections_id = $request->sections_id;
$categories->save();
// records in pivot table users_categories
$user = Sentinel::getUser()->id;
$users_categories = new CategorieUser();
$users_categories->user_id = $user;
$users_categories->categorie_id = $categories->id;
$users_categories->save();
return redirect()->route('categories.index');
}
}
This is the form:
<form action="store" method="POST">
<div class="form-group">
<label for="section">Choose section:</label>
<select class="form-control" name="sections_id">
#foreach($sections as $section)
<option value="{{ $section->id }}">{{ $section->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="name">Category name:</label>
<input type="text" class="form-control" name="name" required>
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<button type="submit" class="btn btn-default">Submit</button>
</form>
This is model Categories.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Categories extends Model
{
public function sections()
{
return $this->belongsTo('App\Models\Sections');
}
public function users()
{
return $this->belongsToMany('App\Models\Users', 'categorie_user');
}
}
And this is model Users.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Users extends Model
{
public function categories()
{
return $this->belongsToMany('App\Models\Categories', 'categorie_user');
}
}
When I add this route under routes as above
Route::group(['prefix' => 'user'], function () {
Route::resource('categories', 'User\CategoriesController');
Route::post('categories/store', ['uses' => 'User\CategoriesController#store']);
});
then everything works like a charm. I'm newbie in Laravel but I think that everything must work with out that route because I use restfull controller. Any sugestions I will appriciated. Thank you.
Finally, I find the answer. According to RESTfull resource controller the URL for form action must be the main route, not /store or /create. So in form action I wrote:
<form action="/user/categories" method="POST">
And that worked for me. Anyway, thanks for help. I hope this will help someone.
change the form action to "/user/categories" like
<form action="/user/categories" method="POST">

Categories