General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into `products`..... in laravel-8 - laravel

i am facing a problem is SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into products (name, detail, color, logo, image, updated_at, created_at) values (fdsf, sdf, #7536d3, 20210522184540.jpg, 20210522184540.JPG, 2021-05-22 18:45:40, 2021-05-22 18:45:40)). i want a user have meny products
here is my ProductController.php
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Admin\StoreTagsRequest;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$products = Product::latest()->paginate(20);
return view('products.index',compact('products'))
->with('i', (request()->input('page', 5) - 1) * 5);
}
function authapi(Request $request)
{
$user = User:: where('email', $request->email)->first();
if(!$user || !Hash::check($request->password, $user->password)){
return response([
'message' => ['These credentials do not match our records.']
],404);
}
$token = $user -> createToken('my-app-token')->plainTextToken;
$response = [
'user' => $user,
'token' => $token
];
return response($response,201);
}
function all_app_jsons(){
return Product::all();
}
function search_by_name($name){
return Product::where('name','like','%'.$name.'%')->get();
}
function search_by_id($id){
return Product::where('id',$id)->get();
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('products.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//$tag = Product::create($request->all());
//return redirect()->route('admin.tags.index');
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'logo' => 'required|mimes:jpeg,png,jpg,gif,svg|max:1024',
]);
$input = $request->all();
if ($image = $request->file('image')) {
$destinationPath = 'image/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image'] = "$profileImage";
}
if ($logo = $request->file('logo')) {
$destinationPath = 'logo/';
$profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
$logo->move($destinationPath, $profileLogo);
$input['logo'] = "$profileLogo";
}
Product::create($input);
return redirect()->route('products.index')
->with('success','Product created successfully.');
}
/**
* Display the specified resource.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function show(Product $product)
{
return view('products.show',compact('product'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function edit(Product $product)
{
return view('products.edit',compact('product'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Product $product)
{
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required'
]);
$input = $request->all();
if ($image = $request->file('image')) {
$destinationPath = 'image/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image'] = "$profileImage";
}else{
unset($input['image']);
}
if ($logo = $request->file('logo')) {
$destinationPath = 'logo/';
$profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
$logo->move($destinationPath, $profileLogo);
$input['logo'] = "$profileLogo";
}else{
unset($input['logo']);
}
$product->update($input);
return redirect()->route('products.index')
->with('success','Product updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function destroy(Product $product)
{
$product->delete();
return redirect()->route('products.index')
->with('success','Product deleted successfully');
}
// function indextwo(){
// //return DB::select("select * from products");
// //DB::table('products')->orderBy('id','desc')->first();
// return Product::orderBy('id', 'DESC')->first();
// }
}
here is my model product.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = [
'name', 'detail', 'image','color','logo'
];
public function user(){
return $this->belongsTo(User::class);
}
}
here is model user.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
'profile_photo_url',
];
public function products(){
return $this->hasMany(Product::class);
}
}
here is product table
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('detail');
$table->string('color');
$table->string('image');
$table->string('logo');
$table->unsignedBigInteger('user_id');
$table->timestamps();
});
Schema::table('products', function (Blueprint $table){
$table->foreign('user_id')->references('id')->on('users');
});
}

I am using Laravel 8 and fixed this error through these two steps:
Move the word from $guarded array to $fillable array in User Mode.
You can put user_id in the $fillable array.
Product
{
fillable=[
'user_id',
... // other attributes
];
}
Or
Product
{
guarded = [];
}
Config.database.php: 'strict' => false in the array of 'mysql'
Note: If your problem is not solved, in your product migration make user_id as nullable.

in this case you must add user_id to $fillable property in Product Model. like this :
protected $fillable = [
'name', 'detail', 'image','color','logo','user_id'
];
Done...

make sure that $fillable in the model has the field 'user_id' like this
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'name',
'detail',
'image',
'color',
'logo'
];
public function user(){
return $this->belongsTo(User::class);
}
}

You need to specify user with id while inserting your data
$data['user_id']=$user->id;
Or Make your column user_id Nullable inthe database.

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')
]);
}

I have an idea to use auth middleware to retrieve a user's products

i have an idea to use auth middleware to retrieve a user's products but currently i am not able to retrieve that user's products. Instead, it listed all the products of other users. Can you guys give me some ideas to help me complete it. Thank you !!!
This is my ProjectController code:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Resources\ProjectResource;
use App\Models\Project;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class ProjectController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$projects = Project::all();
return response([
'projects' => ProjectResource::collection($projects),
'message' => 'Retrieved successfully'
], 200);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$data = $request->all();
$validator = Validator::make($data, [
// 'uuid' => 'required|unique:projects',
'user_id' => 'required',
'name' => 'required|max:255',
'status' => 'required',
]);
if ($validator->fails()) {
return response(['error' => $validator->errors(), 'Validation Error']);
}
$projects = Project::create($data);
return response(['projects' => new ProjectResource($projects), 'message' => 'Created successfully'], 201);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show(Project $project)
{
return response(['project' => new ProjectResource($project), 'message' => 'Retrieved successfully'], 200);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Project $project)
{
$project->update($request->all());
return response(['project' => new ProjectResource($project), 'message' => 'Update successfully'], 200);
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy(Project $project)
{
$project->delete();
return response(['message' => 'Deleted'], 204);
}
}
This is my ProjectModel code:
<?php
namespace App\Models;
use App\Enums\ProjectStatus;
use App\Http\Traits\Uuid;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Project extends Model
{
use HasFactory;
use Uuid;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'status',
'user_id',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'id',
'uuid',
];
protected $cast = [
'status' => ProjectStatus::class
];
public function setUuidAttribute()
{
$this->attributes['uuid'] = Str::uuid();
}
}
This is my API Router code:
You have to retrieve the user first in order to filter the products. There are multiple ways to do that. Here's a link to Laravel's documentation on the subject: https://laravel.com/docs/8.x/authentication#retrieving-the-authenticated-user
You also have to filter your query (your query being Project::all()) so that it only retrieves the products for the user. Here's a link to some Laravel documentation related to that: https://laravel.com/docs/8.x/eloquent#retrieving-models
In the end, replacing this $projects = Project::all(); with this $projects = Project::where('user_id', auth()->user()->id); should do the trick.
Try this
public function index()
{
$projects = Project::where('user_id', auth()->id())->get();
return response([
'projects' => ProjectResource::collection($projects),
'message' => 'Retrieved successfully'
], 200);
}

Trying to store and edit product for specific user id

Here I am trying to store and edit the product for a specific id. Wher a user can have some product and those products can be edit for this specific user. I have tried to do this but don't know what`s the problem is happening. can someone help me. Thanks in advance
this is my ProductController.php
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Admin\StoreTagsRequest;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$products = Product::latest()->paginate(20);
return view('products.index',compact('products'))
->with('i', (request()->input('page', 5) - 1) * 5);
}
function authapi(Request $request)
{
$user = User:: where('email', $request->email)->first();
if(!$user || !Hash::check($request->password, $user->password)){
return response([
'message' => ['These credentials do not match our records.']
],404);
}
$token = $user -> createToken('my-app-token')->plainTextToken;
$response = [
'user' => $user,
'token' => $token
];
return response($response,201);
}
function all_app_jsons(){
return Product::all();
}
function search_by_name($name){
return Product::where('name','like','%'.$name.'%')->get();
}
function search_by_id($id){
return Product::where('id',$id)->get();
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('products.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//$tag = Product::create($request->all());
//return redirect()->route('admin.tags.index');
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'logo' => 'required|mimes:jpeg,png,jpg,gif,svg|max:1024',
]);
$input = $request->all();
// $request->validated();
$input['user_id'] = auth()->user()->id;
if ($image = $request->file('image')) {
$destinationPath = 'image/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image'] = "$profileImage";
}
if ($logo = $request->file('logo')) {
$destinationPath = 'logo/';
$profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
$logo->move($destinationPath, $profileLogo);
$input['logo'] = "$profileLogo";
}
Product::create($input);
return redirect()->route('products.index')
->with('success','Product created successfully.');
}
/**
* Display the specified resource.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function show(Product $product)
{
return view('products.show',compact('product'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function edit(Product $product)
{
return view('products.edit',compact('product'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
// public function update(Request $request, Product $product)
public function update(Request $request, $productId)
{
$product = auth()->user()->products()->findOrFail($productId);
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required'
]);
$input = $request->all();
if ($image = $request->file('image')) {
$destinationPath = 'image/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image'] = "$profileImage";
}else{
unset($input['image']);
}
if ($logo = $request->file('logo')) {
$destinationPath = 'logo/';
$profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
$logo->move($destinationPath, $profileLogo);
$input['logo'] = "$profileLogo";
}else{
unset($input['logo']);
}
$product->update($input);
return redirect()->route('products.index')
->with('success','Product updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function destroy(Product $product)
{
$product->delete();
return redirect()->route('products.index')
->with('success','Product deleted successfully');
}
// function indextwo(){
// //return DB::select("select * from products");
// //DB::table('products')->orderBy('id','desc')->first();
// return Product::orderBy('id', 'DESC')->first();
// }
}
in ProductController.php $product = auth()->user()->products()->findOrFail($productId); in this line said products() id undefined
this is my model Product.php
class Product extends Model
{
use HasFactory;
protected $fillable = [
'name', 'detail', 'image','color','logo','user_id'
];
public function user(){
return $this->belongsTo(User::class);
}
}
This is my User.php model
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
'profile_photo_url',
];
public function products(){
return $this->hasMany(Product::class);
}
}
This is product table
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('detail');
$table->string('color');
$table->string('image');
$table->string('logo');
$table->unsignedBigInteger('user_id')->nullable();
$table->timestamps();
});
Schema::table('products', function (Blueprint $table){
$table->foreign('user_id')->references('id')->on('users');
});
}
Note: I can store many products but not for specific users. I can store and edit product every user can access it. But I want a specific user will have some product where other user cant acess
$table->unsignedBigInteger('product_id')->references('id')->on('products')->onDelete('cascade');
I userd This on projects table

I get BadMethodCallException Call to undefined method App\Models\User::identifiableAttribute()

I get this error after clicking 'New Post' button the frontend of the app:
Posts view
Line from my log file:
[2020-09-27 14:41:03] local.ERROR: Call to undefined method App\Models\User::identifiableAttribute() {"exception":"[object] (BadMethodCallException(code: 0): Call to undefined method App\Models\User::identifiableAttribute() at C:\xampp\htdocs\backpack-demo\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php:50)
I am using Laravel 7 + Backpack CRDU generator
Posts Controller:
<?php
namespace App\Http\Controllers;
use App\Events\NewPost;
use App\Http\Requests\PostStoreRequest;
use App\Jobs\SyncMedia;
use App\Mail\ReviewPost;
use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
class PostController extends Controller
{
/**
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function index(Request $request)
{
$posts = Post::all();
return view('post.index', compact('posts'));
}
/**
* #param \App\Http\Requests\PostStoreRequest $request
* #return \Illuminate\Http\RedirectResponse
*/
public function store(PostStoreRequest $request)
{
$post = Post::create($request->validated());
Mail::to($post->author->email)->send(new ReviewPost($post));
SyncMedia::dispatch($post);
event(new NewPost($post));
$request->session()->flash('post.title', $post->title);
return redirect()->route('post.index');
}
}
Posts Model:
class Post extends Model
{
use CrudTrait;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'title',
'content',
'published_at',
'author_id',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'id' => 'integer',
'author_id' => 'integer',
];
/**
* The attributes that should be mutated to dates.
*
* #var array
*/
protected $dates = [
'published_at',
];
public static function create(array $validated)
{
}
public function author()
{
return $this->belongsTo(User::class);
}
}
User model:
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
your have forgotten to use 'CrudTrait' in your User Model:
use Backpack\CRUD\app\Models\Traits\CrudTrait;
class User extends Authenticatable
{
use Notifiable,CrudTrait
.......
}

Showing posts from specific user in Laravel

I have a question about showing posts from specific user. I'm building a basic keeping records website for my brothers company. I made a redirected login for normal users(workers in company) and for admin(company manager). So I'm new at Laravel and programming, a did everything for this website and all I need is how to show posts on admin profile for specific user. On admin profile I'll make pages for all workers profiles and on specific page I need to show posts for that specific user. How can I do that? Making new Controller?
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Post;
class PostsController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$post = Post::all();
return view('posts.tabela')->with('posts', $post);
}
/**
* 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)
{
$this->validate($request, [
'br_kesice' => 'required',
'ime' => 'required',
'br_telefona' => 'required',
'posao' => 'required',
'cijena' => 'required',
'placanje' => 'required',
'popust' => 'required',
'datum_preuz' => 'required',
'datum_izdav' => 'required',
'smjena' => 'required',
'radnik' => 'required',
'status' => 'required'
]);
$post = new Post;
$post->br_kesice = $request->input('br_kesice');
$post->ime = $request->input('ime');
$post->br_telefona = $request->input('br_telefona');
$post->posao = $request->input('posao');
$post->cijena = $request->input('cijena');
$post->placanje = $request->input('placanje');
$post->popust = $request->input('popust');
$post->datum_preuz = $request->input('datum_preuz');
$post->datum_izdav = $request->input('datum_izdav');
$post->smjena = $request->input('smjena');
$post->radnik = $request->input('radnik');
$post->status = $request->input('status');
$post->user_id = auth()->user()->id;
$post->save();
return redirect('/home');
}
/**
* 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)
{
$post = Post::find($id);
if(auth()->user()->id !==$post->user_id){
return redirect('/posts')->with('error', 'Nedozvoljen pristup!');
}
return view('posts.edit', compact('post', 'id'))->with('post', $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)
{
$this->validate($request, [
'br_kesice' => 'required',
'ime' => 'required',
'br_telefona' => 'required',
'posao' => 'required',
'cijena' => 'required',
'placanje' => 'required',
'popust' => 'required',
'datum_preuz' => 'required',
'smjena' => 'required',
'radnik' => 'required',
'status' => 'required'
]);
$post = Post::find($id);
$post->br_kesice = $request->input('br_kesice');
$post->ime = $request->input('ime');
$post->br_telefona = $request->input('br_telefona');
$post->posao = $request->input('posao');
$post->cijena = $request->input('cijena');
$post->placanje = $request->input('placanje');
$post->popust = $request->input('popust');
$post->datum_preuz = $request->input('datum_preuz');
$post->datum_izdav = $request->input('datum_izdav');
$post->smjena = $request->input('smjena');
$post->radnik = $request->input('radnik');
$post->status = $request->input('status');
$post->save();
return redirect('/home');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\User;
class Post extends Model
{
protected $table = 'posts';
public $primaryKey = 'id';
public $timestamps = true;
public function user(){
return $this->belongsTo('App\User');
}
}
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Post;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function posts(){
return $this->hasMany('App\Post');
}
public function is_admin(){
if($this->admin)
{
return true;
}
return false;
}
}

Resources