I can't store category_id on table - laravel

I cannot get category_id when I created a topic. Here are my codes and mysql. I think I have a problem in store method on forum controller.
mysql pro screenshot
Topic create page
#extends('app')
#section('content')
<h1>トピック</h1>
<hr>
{!! Form::open(['url' => 'forums']) !!}
<div class="form-group">
{!! Form::label('title', 'タイトル:') !!}
{!! Form::text('title', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('body', '本文:') !!}
{!! Form::textarea('body', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('category', 'カテゴリー:') !!}
{!! Form::select('category', $categories,null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('送信',['class' => 'btn btn-primary form-control']) !!}
</div>
{!! Form::close() !!}
#stop
forums controller
<?php
namespace App\Http\Controllers;
use App\Category;
use App\User;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use App\Topic;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ForumsController extends Controller
{
public function index()
{
$categories = Category::all();
$topics = Topic::latest()->get();
return view('forums.index',compact('categories','topics'));
}
public function create()
{
$categories = Category::lists('title', 'id');
return view('forums.create', compact('categories'));
}
public function store(Request $request)
{
Auth::user()->topics()->save(new Topic($request->all()));
// flash()->success('投稿しました','success');
// return redirect('forums');
}
}
Category model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = [
'title'
];
public function topics()
{
return $this->hasMany('App\Topic');
}
}
Topic model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class topic extends Model
{
protected $fillable = [
'title',
'body'
];
public function category()
{
return $this->belongsTo('App\category');
}
public function user()
{
return $this->belongsTo('App\User');
}
}

Add category_id to the topic's Model fillable array like this
protected $fillable = [
'title',
'body',
'category_id'
];

Related

Laravel - 403 redirect. Redirect is correct working for tags and category sections but not for users

I'm trying to set the post admin section. The mission for that section is to show all articles that belong to logged user. The way I'm doing for tags and categories is working correct (tags and categories doesn't need to be filtered for any user). The post page works correctly show the owned post for logged user, but the problem is that the user can't edit or show any post and trying to store a new post redirects to 403 page. I'm confuse by the error and I don't have any solution. I appreciate some help.
PostModel
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable = [
'user_id', 'category_id', 'name', 'slug', 'excerpt', 'body', 'status', 'file'
];
public function category()
{
return $this->belongsTo(Category::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function tags()
{
return $this->belongsToMany(Tag::class);
}
}
PostController
<?php
namespace App\Http\Controllers\Admin;
use App\Models\Post;
use App\Models\Category;
use App\Models\Tag;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\PostStoreRequest;
use App\Http\Requests\PostUpdateRequest;
use Illuminate\Support\Facades\Storage;
class PostController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$posts = Post::orderBy('id', 'DESC')
->where('user_id', auth()->user()->id)
->paginate();
return view('admin.posts.index', compact('posts'));
}
public function create()
{
$categories = Category::orderBy('name', 'ASC')->pluck('name', 'id');
$tags = Tag::orderBy('name', 'ASC')->get();
return view('admin.posts.create', compact('categories', 'tags'));
}
public function store(PostStoreRequest $request)
{
$post = Post::create($request->all());
$this->authorize('pass', $post);
//IMAGE
if($request->file('image')){
$path = Storage::disk('public')->put('image', $request->file('image'));
$post->fill(['file' => asset($path)])->save();
}
//TAGS
$post->tags()->attach($request->get('tags'));
return redirect()->route('posts.edit', $post->id)->with('info', 'Success');
}
public function show($id)
{
$post = Post::find($id);
$this->authorize('pass', $post);
return view('admin.posts.show', compact('post'));
}
public function edit($id)
{
$categories = Category::orderBy('name', 'ASC')->pluck('name', 'id');
$tags = Tag::orderBy('name', 'ASC')->get();
$post = Post::find($id);
$this->authorize('pass', $post);
return view('admin.posts.edit', compact('post', 'categories', 'tags'));
}
public function update(PostUpdateRequest $request, $id)
{
$post = Post::find($id);
$this->authorize('pass', $post);
$post->fill($request->all())->save();
//IMAGE
if($request->file('image')){
$path = Storage::disk('public')->put('image', $request->file('image'));
$post->fill(['file' => asset($path)])->save();
}
//TAGS
$post->tags()->sync($request->get('tags'));
return redirect()->route('posts.edit', $post->id)->with('info', 'Success');
}
public function destroy($id)
{
$post = Post::find($id)->delete();
$this->authorize('pass', $post);
return back()->with('info', 'Deleted');
}
}
PostUpdateRequest
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class PostUpdateRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
$rules = [
'name' => 'required',
'slug' => 'required|unique:posts,slug,' . $this->post,
'user_id' => 'required|integer',
'category_id' => 'required|integer',
'tags' => 'required|array',
'body' => 'required',
'status' => 'required|in:DRAFT,PUBLISHED',
];
if($this->get('image'))
$rules = array_merge($rules, ['image' => 'mimes:jpg,jpeg,png']);
return $rules;
}
}
PostStoreRequest
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class PostStoreRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
$rules = [
'name' => 'required',
'slug' => 'required|unique:posts,slug',
'user_id' => 'required|integer',
'category_id' => 'required|integer',
'tags' => 'required|array',
'body' => 'required',
'status' => 'required|in:DRAFT,PUBLISHED',
];
if($this->get('image'))
$rules = array_merge($rules, ['image' => 'mimes:jpg,jpeg,png']);
return $rules;
}
}
And for example, the post.edit
#extends('admin.admin')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="card">
<div class="card-header">
{{ __('Editar artículo') }}
</div>
<div class="card-body">
{!! Form::model($post, ['route' => ['posts.update', $post->id], 'method' => 'PUT']) !!}
#include('admin.posts.partials.form')
{!! Form::close() !!}
</div>
</div>
</div>
</div>
</div>
#endsection
And finally the form
<div class="form-group">
{{ Form::hidden('user_id', auth()->user()->id) }}
</div>
<div class="form-group">
{{ Form::label('category_id', 'Category') }}
{{ Form::select('category_id', $categories, null, ['class' => 'form-control']) }}
</div>
<div class="form-group">
{{ Form::label('name', 'Tag name') }}
{{ Form::text('name', null, ['class' => 'form-control', 'id' => 'name']) }}
</div>
<div class="form-group">
{{ Form::label('slug', 'URL friendly') }}
{{ Form::text('slug', null, ['class' => 'form-control', 'id' => 'slug']) }}
</div>
<div class="form-group">
{{ Form::label('image', 'Image') }}
{{ Form::file('image') }}
</div>
<div class="form-group">
{{ Form::label('slug', 'State') }}
<label>
{{ Form::radio('status', 'PUBLISHED') }} Published
</label>
<label>
{{ Form::radio('status', 'DRAFT') }} Draft
</label>
</div>
<div class="form-group">
{{ Form::label('tags', 'Tags') }}
<div>
#foreach($tags as $tag)
<label>
{{ Form::checkbox('tags[]', $tag->id) }} {{ $tag->name }}
</label>
#endforeach
</div>
</div>
<div class="form-group">
{{ Form::label('excerpt', 'Excerpt') }}
{{ Form::textarea('excerpt', null, ['class' => 'form-control', 'rows' => '2']) }}
</div>
<div class="form-group">
{{ Form::label('body', 'Description') }}
{{ Form::textarea('body', null, ['class' => 'form-control']) }}
</div>
<div class="form-group">
{{ Form::submit('Guardar', ['class' => 'btn btn-sm btn-primary']) }}
</div>
#section('scripts')
<script src="{{ asset('components/stringToSlug/jquery.stringToSlug.min.js') }}"></script>
<script>
$(document).ready(function(){
$("#name, #slug").stringToSlug({
callback: function(text){
$('#slug').val(text);
}
});
});
</script>
#endsection
Sorry for the extension but it was necessary to explain the problem.
The authorize() method in controller method looks for a corresponding policy. If Laravel can't find the corresponding policy it throws unauthenticated exception.
So in this case $this->authorize('pass', $post), expects to find a PostPolicy class, otherwise it will throw unauthorized exception which is converted to 403 redirect by middleware.
Read more about Policies https://laravel.com/docs/8.x/authorization#creating-policies.
Note: When using FormRequest to handle validation, authorization can be done in FormRequest and there's not need to duplicate authorization in controller method

Search query through foreign key

I'm trying to search through my comments on the username connected to the user_id Foreign Key
Tables:
Comment- id, comment, user_id, timestamps
User - id, name, username
Models:
class Comment extends Model
{
public function author()
{
return $this->belongsTo('App\User','user_id');
}
}
Controller:
public function index(Request $request)
{
$comments = Comment::query()->orderby('created_at', 'DESC');
$id=$request->]
return view('comments.index')->withComment($comment);
}
View:
<div class="panel-body">
{!! Form::open(['route' => 'comments.index', 'method' => 'GET']) !!}
<div class="col-md-5">
{!! Form::label('id', 'Search By ID:') !!}
{!! Form::text('id', null, array('class' => 'form-control')) !!}
</div>
<div class="col-md-5">
{!! Form::label('username', 'Search By Username:') !!}
{!! Form::text('username', null, array('class' => 'form-control')) !!}
</div>
<div class="col-md-2">
{!! Form::submit('Find Comments', array('class' => 'btn btn-send ')) !!}
</div>
{!!Form::close()!!}
</div>
#foreach($comment as $comments)
//data
#endforeach
I believe it is failing at the builder level because you are trying to query on an object that is not yet known. IE the author LIKE must be part of a sub query:
$comments = Comment::whereHas('author', function ($query) use($request) {
$query->where(users.username, 'LIKE', $request->input('username') )
}])->orderby('created_at', 'DESC')->get();
I see you will have to write the query a second time, but I think this may be successful for you.

update user avatar with laravel5

From the look of it seems to me very logic but I am missing something, it doesn't work, nothing changes!
Here is my profile controller file:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use Image;
class ProfileController extends Controller
{
public function profile()
{
$user = Auth::user();
return view('profile')->with('user', $user);
}
public function edit()
{
$user = Auth::user();
return view('edit')->with('user', $user);
}
public function update(Request $request)
{
if($request->hasFile('avatar'))
{
$avatar = $request->file('avatar');
$filename = time().'.'.$avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300, 300)->save(public_path('/uploads/users_avatars/'.$filename));
$user = Auth::user();
$user->avatar = $filename;
$user->save();
}
return redirect('profile')->with('user', Auth::user());
}
}
and here is my edit.blade.php
#extends('layouts.app')
#section('content')
<div class="col-md-6">
{!! Form::model($user, ['method'=>'PATCH', 'action'=>'ProfileController#update', 'file'=>'true']) !!}
<div class="form-group">
{!! Form::label('name', 'Name') !!}
{!! Form::text('name', null, ['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('email', 'Email') !!}
{!! Form::email('email', null, ['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('number', 'Phone') !!}
{!! Form::text('number', null, ['class'=>'form-control']) !!}
</div>
<div class="form-group col-md-5">
{!! Form::label('avatar', 'Avatar') !!}
{!! Form::file('avatar', ['class'=>'form-control']) !!}
</div><br><br><br><br>
<div class="form-group">
{!! Form::submit('Update', null, ['class'=>'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
</div>
#stop
but when I edit the user it doesn't change..plz help
It seems like you have made a mistake while using Form from Laravel HTML Collective. You should use "files" => true instead of "file" => true
{!! Form::model($user, ['method'=>'PATCH', 'action'=>'ProfileController#update', 'file'=>'true']) !!}

Laravel 5.2 controller index returns blank page

I created a route to a simple contact page. I use a controller to save the data in the database and display them on the same page. When I submit the form I get a blank page but I want the user to stay on the contact. I tried to pass the index view but then I get errors.
The files are
route.php
Route::get('contact', 'ContactController#index');
Route::post('contact', 'ContactController#create');
ContactController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Contact;
class ContactController extends Controller
{
public function index() {
$contacts = Contact::orderBy('created_at', 'asc')->get();
return view('/contact', [ 'contacts' => $contacts ]);
}
public function create(Request $request) {
$name = $request->input('name');
$contact = new Contact;
$contact->name = $name;
$contact->save();
#return view('/contact');
}
}
Contact.php
<?php
Namespace App;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
protected $fillable = ['name'];
}
?>
contact.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Contact page</div>
<div class="panel-body">
{!! Form::open(array('url' => 'contact')) !!}
{!! Form::label('name', 'Name') !!}
{!! Form::text('name'); !!}
{!! Form::submit('Submit'); !!}
{!! Form::close() !!}
#if (count($contacts) > 0)
#foreach ($contacts as $contact)
{{ $contact->name }}
#endforeach
#endif
</div>
</div>
</div>
</div>
</div>
#endsection
Try to put contact.blade.php inside views folder and use view('contact', [...]) instead of view('/contact');, you don't need the slash and add return back() to create method:
public function create(Request $request) {
$name = $request->input('name');
$contact = new Contact;
$contact->name = $name;
$contact->save();
return back();
}

MethodNotAllowedHttpException in RouteCollection.php line 219 in Laravel

I have used illuminate/html in laravel to create a form and insert data to it.
this is my routes.php:
Route::post('/userlog', 'LogController#userlog');
this is my view:
#extends('layouts.master')
#section('content')
{!! Form::open(['url' => '/userlog']) !!}
<div class="form-group">
{!! Form::label('phone', 'User phone:') !!}
{!! Form::text('phone', null, ['class' => 'form-control input-sm']) !!}
</div>
{!! Form::close() !!}
#endsection
and this is the controller:
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Requests;
class LogController extends Controller
{
public function userlog(Request $request)
{
$input = $request::all();
print_r($input);die();
}
}
I face this error:
MethodNotAllowedHttpException in RouteCollection.php line 219:
What is the problem?

Resources