I am trying to allow users to edit posts, however I keep getting this error:
Property [caption] does not exist on this collection instance. (View: C:\xampp\htdocs\myprojectname\resources\views\posts\edit-post.blade.php)
My edit function in Post Controller is:
use App\Models\Post;
public function edit(Post $post)
{
return view('posts.edit-post', ['post' => $post]);
}
My update function in Post Controller is:
public function update(Post $post, Request $request)
{
$data = request()->validate([
'caption' => 'nullable',
'url' => 'nullable',
'image' => 'nullable',
]);
$updateData = [
'caption' => $data['caption'],
'url' => $data['url'],
];
if (request('image')) {
$imagePath = request('image')->store('uploads', 'public');
$updateData['image'] = $imagePath;
}
auth()->user()->posts()->id()->update($updateData);
return redirect('/users/' . auth()->user()->id);
}
My edit-post.blade.php file code is:
#section('content')
<body class="create_body">
<div class="create_container_div">
<form action="{{('/users/' . auth()->user()->id)}}" enctype="multipart/form-data" method="post">
#csrf
#method('PATCH')
<div class="form-group">
<label for="caption" class="create_caption_label">Post Caption</label>
<div class="create_caption_div">
<input id="caption"
type="text"
class="form-control #error('caption') is-invalid #enderror"
name="caption"
value="{{ old('caption') ?? auth()->user()->posts->caption }}"
autocomplete="caption" autofocus>
#error('caption')
<div class="invalid-feedback-div">
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
</div>
#enderror
</div>
</div>
<div class="form-group">
<label for="url" class="edit_title_label">URL</label>
<div class="edit_url_div">
<input id="url"
type="text"
class="form-control #error('url') is-invalid #enderror"
name="url"
value="{{ old('url') ?? auth()->user()->posts->url }}"
autocomplete="url" autofocus>
#error('url')
<div class="invalid-feedback-div">
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
</div>
#enderror
</div>
</div>
<div class="create_post_image_div">
<label for="image" class="create_image_label">Post Image</label>
<input type="file" class="form-control-file" id="image" name="image">
#error('image')
<div class="invalid-feedback-div">
<strong>{{ $message }}</strong>
</div>
#enderror
<div class="create_post_btn_div">
<button class="create_post_btn">Save Changes</button>
</div>
</div>
</form>
</div>
</body>
#endsection
My create_posts_table migration file is:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('caption');
$table->string('url');
$table->string('image');
$table->timestamps();
$table->index('user_id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
And my Post.php model file is:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
}
Finally my routes in web.php are:
use App\Http\Controllers\PostsController;
Route::get('/posts/{post}/edit', [PostsController::class, 'edit']);
Route::patch('/posts/{post}', [PostsController::class, 'update'])->name('posts.update');
How can I resolve this issue, and furthermore, how do I allow users to edit posts?
This line is not correct, i don't know if you are coming from some other language, this makes no sense at all for me.
auth()->user()->posts()->id()->update($updateData);
You have the Post already in the context you are, due to it being Model bound in your controller method public function update(Post $post, Request $request), you can use that to just update it. fill() applies you $updateData to the model and save() writes it to the database.
$post->fill($updateData);
$post->save();
As the comments stated, the edit function is missing an id, again you have already bound your model to the method, then just use it.
public function edit(Post $post)
{
return view('posts.edit-post', ['post' => $post]);
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I try to make registeration system for binary look like as picture
here is registercontroller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\MemberExtra;
use Carbon\Carbon;
use Illuminate\Support\Facades\Session;
use Illuminate\Auth\Events\Registered;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('guest');
}
public function index()
{
return view('users.register');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
protected function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
'referrer_id' => 'required',
'position' => 'required',
'name' => 'required',
]);
}
protected function create(array $data)
{
$pin = substr(time(), 4);
$ref_id = $data['referrer_id'];
$poss = $data['position'];
$posid = getLastChildOfLR($ref_id,$poss);
return User::create([
'email' => $data['email'],
'password' => bcrypt($data['password']),
'referrer_id' => $data['referrer_id'],
'position' => $data['position'],
'name' => $data['name'],
'join_date' => Carbon::today(),
'posid' => $posid,
]);
}
public function signup(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
MemberExtra::create([
'user_id' => $user['id'],
'left_paid' => 0,
'right_paid' => 0,
'left_free' => 0,
'right_free' => 0,
'left_bv' => 0,
'right_bv' => 0,
]);
updateMemberBelow($user['id'], 'FREE');
return $this->registered($request, $user) ?: redirect()->route('users.register');
}
}
modes
protected $fillable = ['referrer_id', 'name', 'password',
'position','join_date',
'email','posid'
];
protected $table ='member_extras';
protected $fillable = [
'user_id',
'left_paid',
'right_paid',
'left_free',
'right_free',
'left_bv',
'right_bv',
];
try to insert data into user and memberarea
but nothing happen.
here is blade form
<h3>Add Users</h3>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<!-- Alert message (start) -->
#if(Session::has('message'))
<div class="alert {{ Session::get('alert-class') }}">
<span style="color:green">{{ Session::get('message') }}</span>
</div>
#endif
<form action="{{route('user.signup')}}" method="POST" id="subjectForm">
{{csrf_field()}}
<div class="col-md-6">
<label for="fullname">Referrer Name</label>
<input class="form-styling" type="text" value="{{old('ref_name')}}" id="ref_name" required placeholder=""/>
<div id="ref">
</div>
#if ($errors->has('referrer_id'))
<span class="help-block">
<strong>{{ $errors->first('referrer_id') }}</strong>
</span>
#endif
</div>
<div class="col-md-6">
<label for="Select Position">Select Position</label>
<select class="select_panel" id="position" name="position" required>
<option disabled selected>Select Position</option>
<option value="L">Left</option>
<option value="R">Right</option>
</select>
<div id="ref_pos">
</div>
#if ($errors->has('position'))
<span class="help-block">
<strong>{{ $errors->first('position') }}</strong>
</span>
#endif
</div>
<div class="col-md-6">
<label for=" First Name">Name</label>
<input value="{{old('name')}}" class="form-styling" required type="text" name="name">
#if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
<div class="col-md-6">
<label for="email">Email</label>
<input type="text" class="form-styling" required name="email" value="{{old('email')}}">
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
<div class="col-md-6">
<label>
Password
</label>
<input required type="password" class="form-styling" name="password">
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
<form action="{{route('login')}}" id="subjectForm">
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</div>
here is migration
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('referrer_id');
$table->string('position');
$table->string('name')->unique();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->integer('posid');
$table->string('join_date');
$table->rememberToken();
$table->timestamps();
});
}
here is database
i inserted admindata manually to call admin username in referrer name when new user signs up. but it does not work.
I copied all codes from binary mlm project source code (laravel 5.5 ver).
How can correctly sign up new user as show in picture?
it show referrer name match and you will join under - someone id.
in my attempt, it does not work.
I am learning how build binary mlm website, i fail in registration phase,
Edited
I get the solution for referrer name and selection position
but when click register buttom
nothing happen
post method not work .also not show any error when register . no data insert to database .
Please check what wrong in controller codes
I see several mistakes that could be a problem,
in blade:
1)
<input class="form-styling" type="text" value="{{old('ref_name')}}" id="ref_name" required placeholder=""/>
there is no name="" parameter
in migration you got $table->string('name')->unique(); Unique but in validation not 'name' => 'required', ,
when you make mass assignment like here $this->validator($request->all())->validate(); event(new Registered($user = $this->create($request->all())));
you can read details here mass assignment , to do so you need to config model $fillable = [] or $guarded = [] parameters to do so, but I had such problem when I used fillable only and I could not do mass assignment anyway and than just used $guarded = [] and worked fine, so just try this as well.
I am trying to allow users to create and add category tags to a post when creating that post in the form.
I would further want those tags to appear in the profile view and function as filter buttons to show posts according to the tag names they possess.
However, in my attempt to achieve this overall result, I am stuck because everytime I submit a post with tags, the tags array keeps showing up empty in the view.
My post table is:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('caption');
$table->string('url');
$table->string('image');
$table->text('tags');
$table->timestamps();
$table->index('user_id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
My Post Model is:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Post extends Model
{
use \Conner\Tagging\Taggable;
use HasFactory;
protected $fillable = ['caption','url','image', 'tags'];
public function user()
{
return $this->belongsTo(User::class);
}
protected $dates = [
'created_at',
'updated_at',
];
}
My create and store methods in PostsController are:
public function create()
{
return view('posts.create');
}
public function store(Request $request)
{
$data = request()->validate([
'caption' => 'required',
'url' => 'required',
'image' => ['required', 'image'],
'tags' => 'required',
]);
$tags = explode(", ", $request->tags);
$imagePath = request('image')->store('uploads', 'public');
auth()->user()->posts()->create([
'caption' => $data['caption'],
'url' => $data['url'],
'image' => $imagePath,
'tags' => $data['tags'],
]);
return redirect('/users/' . auth()->user()->id);
}
My form to create post is:
<form action="/posts" enctype="multipart/form-data" method="post">
#csrf
<div class="form-group">
<label for="caption" class="create_caption_label">Post Caption</label>
<div class="create_caption_div">
<input id="caption"
type="text"
class="form-control #error('caption') is-invalid #enderror"
name="caption"
value="{{ old('caption') ?? '' }}"
autocomplete="caption" autofocus>
#error('caption')
<div class="invalid-feedback-div">
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
</div>
#enderror
</div>
</div>
<div class="form-group">
<label for="tags" class="create_tags_label">Tags</label>
<div class="create_tags_div">
<input id="tags"
type="text"
data-role="tagsinput"
class="form-control #error('tags') is-invalid #enderror"
name="tags"
value="{{ old('tags') ?? '' }}"
autocomplete="tags" autofocus>
#error('tags')
<div class="invalid-feedback-div">
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
</div>
#enderror
</div>
</div>
<div class="form-group">
<label for="url" class="edit_title_label">URL</label>
<div class="edit_url_div">
<input id="url"
type="text"
class="form-control #error('url') is-invalid #enderror"
name="url"
value="{{ '' }}"
autocomplete="url" autofocus>
#error('url')
<div class="invalid-feedback-div">
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
</div>
#enderror
</div>
</div>
<div class="create_post_image_div">
<label for="image" class="create_image_label">Post Image</label>
<input type="file" class="form-control-file" id="image" name="image">
#error('image')
<div class="invalid-feedback-div">
<strong>{{ $message }}</strong>
</div>
#enderror
<div class="create_post_btn_div">
<button class="create_post_btn">Save Post</button>
</div>
</div>
</form>
Finally, my view is: (This is where the tags array shows up empty after submitting a post)
#foreach( $user->posts as $post )
<div class="carousel_posts_container">
<div class="post_date_and_edit_div">
<div class="posted_date_div">
<p class="posted_date">posted: {{ $post->created_at->diffForHumans() }}</p>
</div>
<div class="post_edit_div">
<form action="/posts/{{$post->id}}/edit">
<input class="post_edit_btn" type="submit" value="• • •">
</form>
</div>
</div>
<div class="post_counter_div">
<p class="post_counter">1 like</p>
</div>
<div class="post_counter_div">
<p class="post_counter">1 comment</p>
</div>
<div class="carousel_post_img_div">
<img src="/storage/{{ $post->image }}" class="carousel_img_placeholder">
</div>
<div class="like_comment_view_container">
<div class="view_btn_div">
<form action="{{$post->url}}">
<input class="like_comment_view_btns" type="submit" value="( View Post )">
</form>
</div>
<div class="like_btn_div">
<button type="button" class="like_comment_view_btns">( Like )</button>
</div>
<div class="comment_btn_div">
<button type="button" class="like_comment_view_btns">( Comment )</button>
</div>
</div>
<div class="carousel_caption_container">
<div class="carousel_caption_div">
<p class="carousel_caption_username">{{$user->username}} - {{$post->caption}}</p>
<p class="carousel_caption">{{$post->caption}}</p>
</div>
<div class="post-tags mb-4">
<strong>Tags : </strong>
#foreach($post->tags as $tag)
<span class="badge badge-info">{{$tag->name}}</span>
#endforeach
</div>
</div>
</div>
#endforeach
How can I resolve this issue?
And furthermore, how can I allow the tags to function as filter buttons to show posts according to the tag names they possess?
You can save tags as json array in db. Then cast to array in model, so it will be automatically array when you will retrieve. When saving you will pass tags as array then it will automatically convert to json string.
protected $casts = [
'tags' => 'array',
];
I'm new to Laravel (I'm using version 8) and I've been reviewing this error for a long time and I don't know what else to try.
I have a resource controller called ** UserController.php ** and I set the path in ** web.php ** as follows:
Route::resource('usuarios', App\Http\Controllers\UsuarioController::class);
The resource paths are:
The user can enter their profile and modify their fields through this menu option that invokes the edit() method of the controller:
So far everything works very well, but when the user enters to edit in the ** edit.blade.php ** form, and selects the "update" button that calls the method ** update () ** of the controller, it jumps to me the error: BadMethodCallException
Method App\Http\Controllers\UsuarioController::update does not exist.
This is edit.blade.php:
#section('title', 'Mi Perfil')
#section('intro')
#endsection
<br><br>
<style type="text/css">
h5 {text-align: center}
nav.navbar {
background-color: #34495E;
}
</style>
#section('content0')
<div class="container3">
<div class="bShadow3 bShadow-33">
<form method="POST" action="{{route('usuarios.update',[Auth::user()->slug]) }}">
#method('PUT')
#csrf
<br>
<h5>Mi perfil</h5>
<div class="form-group ml-5 mr-5">
<label for="name">{{ __('Nombre de usuario') }}</label>
<input id="name" type="text" class="form-control #error('name') is-invalid #enderror" name="name" value="{{Auth::user()->name}}" autocomplete="name" maxlength="30" autofocus placeholder="Introduce tu nombre de usuario" required>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="form-group ml-5 mr-5">
<label for="name">{{ __('Dirección de correo:') }}</label><br>
<label for="email">{{Auth::user()->email}}</label>
</div>
<div class="form-group row mb-0">
<div class="col text-center">
<button type="submit" class="btn2 mt-2 mb-3">
{{ __('Actualizar') }}
</button>
<button type="default" class="btn2 mt-2 mb-3">
{{ __('Cancelar') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
This is UsuarioController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use App\Models\Role;
class UsuarioController extends Controller
{
public function __construct()
{
//permitir solo usuarios autenticados
$this->middleware('auth');
}
public function index()
{
//
}
public function create()
{
//
}
public function store(Request $request)
{
}
public function show($id)
{
}
public function edit($id)
{
$usuario=User::find($id);
if ($usuario== null)
return Redirect::to('usuario');
return view('usuarios.edit')->with('id',$id);
}
public function update(Request $request, $id)
{
$user = User::find($id);
$user->name = Input::get('name');
$user->email = Input::get('email');
$user->password = Input::get('password');
$user->save();
}
public function destroy($id)
{
//
}
}
If someone can give me a hand, I will thank them very much!
Thanks for the answers, I already fixed the error.
I had two controllers using the same controller class and I was working with one and laravel with another.
I do not know exactly where the problem comes from but I think
1: change route
{{route('usuarios.update',auth()->user()) }}
2: It needs a model but you send slug usuarios/{usuario}
I am working on a pet registration platform, but when I click on the submit button to save the info to my database, I seem to get this error:
SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: pets.user_id (SQL: insert into "pets" ("nickname", "species", "date_of_birth", "user_id", "updated_at", "created_at") values (Tom, Male, 2009-07-30, ?, 2020-12-13 09:59:07, 2020-12-13 09:59:07))
This is the Pets Controller:
<?php
namespace App\Http\Controllers;
use App\Models\Pet;
use App\Models\User;
class PetsController extends Controller
{
public function create()
{
return view('create');
}
public function store(User $user)
{
Pet::create([
'nickname' => request('nickname'),
'species' => request('species'),
'date_of_birth' => request('date_of_birth'),
'color' => request('color'),
'description' => request('description'),
'user_id' => $user->id
]);
return redirect('/');
}
}
This is the Model for User:
<?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;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'username',
'phone',
'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 pets()
{
return $this->hasMany(Pet::class);
}
This is the model for Pets:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Pet extends Model
{
protected $fillable = ['nickname','species','date_of_birth','gender','user_id'];
public function users()
{
return $this->belongsTo(User::class);
}
}
This is the form view:
#extends('layouts.app')
#section('content')
<div class="container py-5">
<form action="/create" enctype="multipart/form-data" method="post">
#csrf
<div class="row">
<div class="col-10">
<div class="row justify-content-center">
<h1><strong>Add A Pet</strong></h1>
</div>
<div class="form-group row py-4">
<label for="nickname" class="col-md-4 col-form-label text-md-right">Nickname</label>
<div class="col-md-6">
<input id="nickname" type="text" class="form-control #error('nickname') is-invalid #enderror"
name="nickname"
value="{{ old('nickname') }}"
placeholder="Enter the name of the animal"
required autocomplete="nickname" autofocus>
#error('nickname')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="species" class="col-md-4 col-form-label text-md-right">Species</label>
<div class="col-md-6">
<select id="species" class="form-control #error('species') is-invalid #enderror"
name="species"
value="{{ old('species') }}"
required autocomplete="species" autofocus>
<option disabled selected>Select species</option>
<option>Dog</option>
<option>Domestic cat</option>
<option>other</option>
</select>
#error('species')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row py-4">
<label for="date_of_birth" class="col-md-4 col-form-label text-md-right">Date of birth</label>
<div class="col-md-6">
<input id="date_of_birth" type="date" class="form-control #error('date_of_birth') is-invalid #enderror"
name="date_of_birth"
value="{{ old('date_of_birth') }}"
placeholder="yyyy-mm-dd"
required autocomplete="date_of_birth" autofocus>
#error('date_of_birth')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row justify-content-center" style="padding-left:108px">
<div class="form-group col-md-3">
<label for="gender">Gender</label>
<select id="species" class="form-control #error('species') is-invalid #enderror"
name="species"
value="{{ old('species') }}"
required autocomplete="species" autofocus>
<option>Unknown</option>
<option>Male</option>
<option>Female</option>
</select>
#error('species')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="form-group col-md-3">
<label for="color">Color</label>
<input id="color" type="text" class="form-control #error('color') is-invalid #enderror"
name="color"
value="{{ old('color') }}"
placeholder="Select color"
required autocomplete="color" autofocus>
#error('color')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row py-4">
<label for="description" class="col-md-4 col-form-label text-md-right">Description</label>
<div class="col-md-6">
<textarea name="description" id="description" rows="3"
class="form-control #error('description') is-invalid #enderror"
value="{{ old('description') }}"
placeholder="Enter a description of the animal"></textarea>
#error('description')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row col-md-6" style="margin-left:300px">
<button class="btn btn-primary btn-lg btn-block">Finish</button>
</div>
<div class="row col-md-6 py-4" style="margin-left:430px">
<u><h4>Add Pet Later</h4></u>
</div>
</div>
</div>
</form>
</div>
#endsection
And finally the migration for pets table:
public function up()
{
Schema::create('pets', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('nickname');
$table->string('species');
$table->date('date_of_birth');
$table->string('gender');
$table->string('color')->nullable();
$table->text('description')->nullable();
$table->timestamps();
});
}
Been struggling with this for quite a while now!
Here is the routes file:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/register/create', [App\Http\Controllers\PetsController::class, 'create']);
Route::post('/create', [App\Http\Controllers\PetsController::class, 'store']);
$user injected in method store() is empty User model without attributes, like after $user = new User;.
You could retrieve current user id with 2 ways:
First: from request.
public function store()
{
Pet::create([
'nickname' => request('nickname'),
'species' => request('species'),
'date_of_birth' => request('date_of_birth'),
'color' => request('color'),
'description' => request('description'),
'user_id' => request()->user()->id
]);
return redirect('/');
}
Second: from auth.
public function store()
{
Pet::create([
'nickname' => request('nickname'),
'species' => request('species'),
'date_of_birth' => request('date_of_birth'),
'color' => request('color'),
'description' => request('description'),
'user_id' => auth()->id()
]);
return redirect('/');
}
Does the pet belong to the user who is logged in? It is not clear where the User instance comes from, in the form action I don't see a user id.
If the pet belongs to the logged in user, why don't you get the id of the user with:
Auth::user()->id; or Auth::id(); or auth()->user()->id;
I'm currently learning Laravel 5.8 and creating instagram clone app and I've been having an issue with updating my profile details. Whenever I hit "Update profile", it gives off an error - "Call to a member function update() on null". The issue seems to be in public function update(). I've looked up other threads and can't seem to fix this issue, so any help would be greatly appreciated!
Here's my code:
View:
#section('content')
<div class="container">
<form action="/profile/{{ $user->id }}" enctype="multipart/form-data" method="post" >
#csrf
#method('PATCH')
<div class="row">
<div class="col-8 offset-2">
<div class="row pb-3">
<h1>Edit profile</h1>
</div>
<div class="form-group row">
<label for="title" class="col-form-label"><strong>Title</strong></label>
<input id="title" type="text" class="form-control #error('title') is-invalid #enderror" name="title" value="{{ old('title') ?? $user->profile['title'] }}" required autocomplete="title" autofocus>
#error('title')
<span class="invalid-feedback" role="alert">
<strong>{{ $title }}</strong>
</span>
#enderror
</div>
<div class="form-group row">
<label for="description" class="col-form-label"><strong>Description</strong></label>
<input id="description" type="text" class="form-control #error('description') is-invalid #enderror" name="description" value="{{ old('description') ?? $user->profile['description']}}" required autocomplete="description" autofocus>
#error('description')
<span class="invalid-feedback" role="alert">
<strong>{{ $description }}</strong>
</span>
#enderror
</div>
<div class="row">
<label for="photo" class="col-form-label">Select Profile Picture</label>
<input type="file" class="form-control-file" id="photo" name="photo">
#error('photo')
<strong>{{ $message }}</strong>
#enderror
</div>
<div class="row pt-3">
<button class="btn btn-primary">
Update Profile
</button>
</div>
</div>
</div>
</form>
</div>
#endsection
Route:
Auth::routes();
Route::get('/profile/{user}', 'ProfileController#index')->name('profile.show');
Route::get('/profile/{user}/edit', 'ProfileController#edit')->name('profile.edit');
Route::patch('/profile/{user}', 'ProfileController#update')->name('profile.update');```
Controller:
<?php
namespace App\Http\Controllers;
use App\User;
use App\Profile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ProfileController extends Controller
{
public function index(User $user){
return view('profile.index', [
'user' => $user,
]);
}
public function edit(User $user){
return view('profile.edit', [
'user' => $user,
]);
}
public function update(User $user){
$data = request()->validate([
'title' => 'required',
'description' => 'required',
'photo' => '',
]);
auth()->user()->profile->update($data);
return redirect("/storage/ {$user->id}");
}
}
Thank you in advance!
try passing the user you are editing as you have passed them in the routes., The error means you want to update a user but you haven't specified which user you are updating.
try doing something like this:
public function validateUser(){
return request()->validate([
'title' => 'required',
'description' => 'required',
'photo' => '',
]);
}
then in the update function do something like this:
public function update($user_id){
return User::where('id',$user_id)->update($this->validateUser());
}
public function update(User $user){
$data = request()->validate([
'title' => 'required',
'description' => 'required',
'photo' => '',
]);
$user->profile()->update($data);
return redirect("/storage/".$user->id);
}
Update Or Insert
Sometimes you may want to update an existing record in the database or create it if no matching record exists. In this scenario, the updateOrInsert method may be used.
User::where('id',$id)->updateOrInsert($data);