I'm new to laravel and I'm learning it from laracast.
Here is my problem, I'm creating a comment form and it's php code looks like this:
<section class="col-span-8 col-start-5 mt-10 space-y-6">
<!-- Post form -->
<form method="POST" action="/post/{{ $post->slug }}/comments" class="border border-gray-200 p-6 rounded-xl">
#csrf
<header class="flex items-center">
<img src="https://i.pravatar.cc/100?id={{ auth()->id() }}" alt="" width="40" height="40" class="rounded-full">
<h2 class="ml-3 ">Want to participate?</h2>
</header>
<div class="mt-6">
<textarea class="w-full text-sm focus:outline-none focus:ring"
name="body"
cols="30" rows="10"
placeholder="Quick,think of something to say!" ></textarea>
</div>
<div>
<button type="submit" class="bg-blue-500 text-white uppercase font-semi-bold text-xs py-2 px-10 rounded-2xl hover:bg-blue-600">Post</button>
</div>
this is the corresponding route:
Route::post('post/{post:slug}/comments',[PostCommentsController::class, 'store']);
Controller:, and I suspect there could be something wrong here 'user_id'=> request()->user()->id, and I tried numerous ways for this approach like auth()->id, Auth::user()->id
<?php
namespace App\Http\Controllers;
use App\Models\Post;
class PostCommentsController extends Controller
{
public function store(Post $post){
request()->validate([
'body'=>'required'
]);
$post->comments()->create([
'user_id'=> request()->user()->id,
'body' => request('body')
]);
return back();
}
}
and this the migration table for comment
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->foreignId('post_id')->constrained()->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->text('body');
$table->timestamps();
migration table for post:
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->foreignId('category_id');
$table->string('slug')->unique();
$table->string('title');
$table->text('excerpt');
$table->text('body');
$table->timestamps();
$table->timestamp('published_at')->nullable();
});
If I click on post button I get the above error,tried my best to solve this problem but I couldn't. Can someone help me what's wrong with my code ?. My question may look naive as I'm new to stackoverflow community
use this code for controller
class PostCommentsController extends Controller
{
public function store(Post $post){
request()->validate([
'body'=>'required'
]);
$post->comments()->create([
'user_id'=> optional(auth()->user())->id,
'body' => request('body')
]);
return back();
}
}
user must logged in
first you must logged in
and in your route you must define your middleware if you are trying to get authenticated user's id like this
Route::post('post/{post:slug}/comments',[PostCommentsController::class, 'store'])->middleware('auth');
after that in your method/function inside controller use 'Request' class(not model class name) when you try to retrieve input from form
Laravel's 'Illuminate\Http\Request' class provides an object-oriented way to interact with the current HTTP request being handled by your application as well as retrieve the input, cookies, and files that were submitted with the request.
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request; //don't forget this
class PostCommentsController extends Controller
{
public function store(Request $request){
request()->validate([
'body'=>'required'
]);
$post->comments()->create([
'user_id'=> auth()->user()->id,
'body' => request('body')
]);
return back();
}
}
Related
hello I have 2 databases, namely users and profiles, profiles has a foreign key that is user_id. Then the relationship between the two is one to one.
Users migration
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Profiles migration
Schema::create('profiles', function (Blueprint $table) {
$table->id();
$table->string('alamat')->nullable();
$table->string('nip')->nullable();
$table->string('jabatan')->nullable();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
User Model
use HasApiTokens, HasFactory, Notifiable;
protected $fillable = [
'name',
'email',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function profile()
{
return $this->hasOne(Profile::class, 'user_id');
}
Profile Model
use HasFactory;
protected $table = 'profiles';
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
Profile Controller
public function render()
{
$userProfile = Profile::where('user_id', Auth::user()->id)->first();
if (!$userProfile) {
$profile = new Profile();
$profile->user_id = Auth::user()->id;
$profile->save();
}
$user = User::find(Auth::user()->id);
return view('profile.index', ['user' => $user]);
}
Profile index.blade.php
<x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Dashboard') }}
</h2>
</x-slot>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
<div class="p-6 bg-white border-b border-gray-200">
Your Profile!
<div>
<p>Nama :{{ $user->name }}</p>
<p>Email : {{ $user->email }}</p>
<p>Alamat : {{ $user->profile->alamat }}</p>
</div>
</div>
</div>
</div>
</div>
the code above produces an error that is Attempt to read property "address" on null. so how do i solve it?
On your render method, you can do something like this:
if(!\Auth::check()){
abort(401);
}
$user = \Auth::user();
$user->load('profile');
return view('profile.index', ['user' => $user]);
The above code is just the optimization with eager loading. This should give you the profile address:
$user->profile->alamat
Three things you have to confirm while doing this:
Is the user authenticated? If the user is not logged in you might not get data.
Is the route wrap in auth or similar middleware? If not, you might not get auth data.
Is there data in profiles table of the current user currently logged in?
I am having trouble showing user profile information in a profile page from the database which gives me Property [name] does not exist on this collection instance. (View: C:\xampp\htdocs\project_one\resources\views\profile.blade.php)
I have attached my code below
Route
Route::get('/profile', function() {
return view('profile', [
"title" => "Profile",
"profile" => Profile::all(),
"user" => User::all()
]);
});
Profile Table
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->id();
$table->string('name')->nullable();
$table->string('email')->unique();
$table->string('address')->nullable();
$table->string('phone')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->timestamps();
});
}
Profile Model
class Profile extends Model
{
use HasFactory;
public function user(){
return $this->belongTo(User::class);
}
}
Function in User Model
public function profile(){
return $this->hasOne(Profile::class);
}
Blade template
<div class="form-group mb-3">
<label for="floatingName">Name</label>
<p>{{ $user->name }}</p>
</div>
your user query "user" => User::all() you are passing to the profile page is the whole users in you DB which is a collection of many users you can't get a specific user name with that......if you want the name of the currently logged in user you will have to use
<div class="form-group mb-3">
<label for="floatingName">Name</label>
<p>{{ auth()->user()->name }}</p>
</div>
without passing the user collection from your route.
or you can also pass the user logged in user through your route with this
Route::get('/profile', function() {
return view('profile', [
"title" => "Profile",
"profile" => Profile::all(),
"user" => auth()->user(),
]);
});
and in your view
<div class="form-group mb-3">
<label for="floatingName">Name</label>
<p>{{ $user->name }}</p>
</div>
Route::get('/profile', function() {
return view('profile', [
"title" => "Profile",
"profile" => Profile::all(),
"user" => User::all() // HERE IS THE PROBLEM
]);
});
User:all() returns collection of all users from the Database, For your case to get specific user on session use auth()->user()
Your Route should look like this
Route::get('/profile', function() {
return view('profile', [
"title" => "Profile",
"profile" => Profile::all(),
"user" => auth()->user(), // HERE IS THE SOLUTION
]);
});
Then you can use variable $user in a blade and get name of specific user
<div class="form-group mb-3">
<label for="floatingName">Name</label>
<p>{{ $user->name }}</p>
</div>
I am new developer, and I seem to be stuck on handling arrays in laravel. I am using Laravel 8, and I cant seem to solve this situation.
I am building an internal recruitment site, where once a manager posts a job, employees will be able to apply to those specific jobs. I have defined the table in the database to have the "applicants" as an array consisting of the user_id's. However, I seem to not be able to add more than one array to it.
Below is my Recruitment Model
class Recruitment extends Model
{
use HasFactory;
protected $fillable = [
'title',
'salary',
'term_start',
'term_end',
'deadline',
'details',
'status',
'applicants',
];
public function user(){
return $this->belongsTo("\App\Models\User");
}
protected $casts = [
'applicants' => 'array'
];
}
Next is my migration (I am using text format, because the DB on the server is older and does not support json)
public function up()
{
Schema::create('recruitments', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->decimal('salary', 10, 2);
$table->date('term_start');
$table->date('term_end');
$table->date('deadline');
$table->longText('details');
$table->string('status');
$table->text('applicants')->nullable();
$table->timestamps();
});
}
Here is my blade
<div class="container">
<div class="row">
<div class="card col-sm-12 py-3">
<div class="card-header border d-flex justify-content-between align-items-center">
<h3 class="w-75">{{ $job->title }}</h3>
<div class="w-25">
<p class="my-0 my-0">Created at: <span class="text-info">{{ $job->created_at }}</span></p>
<p class="my-0 my-0">Last updated at: <span class="text-primary">{{ $job->updated_at }}</span></p>
</div>
</div>
<div class="card-body">
// display job details here
<form action="{{ route('add-applicant', ['id' => $job->id ]) }}" method="POST" class="col-sm-12 d-flex justify-content-center align-items-center">
#csrf
<input type="text" name="user_id" id="user_id" value="{{ Auth::user()->id }}" hidden>
<button type="submit" class="btn btn-success w-25">Apply</button>
</form>
</div>
</div>
</div>
</div>
and lastly my controller
public function addApplicant($id, Request $reqst){
$job = Recruitment::find($id);
$user[] = $reqst->user_id;
$job->applicants = $user;
$job->save();
return redirect()->back();
}
While this controller will be able to save an array, it unfortunately overwrites the already existing one (let's say a second user applied). When I try to use an array_push, it does nothing, and I still end up with just one value in the array.
Sorry this was a bit of a read, but I appreciate any help I cen get with this. Thanks
Try in
public function addApplicant($id, Request $reqst){
$job = Recruitment::find($id);
$job->applicants = $reqst->user_id;
$job->save();
return redirect()->back();
}
and in Recruitment model should have
public function user()
{
return $this->belongsTo(User::class, 'applicants');
}
and migration file
$table->integer('applicants')->nullable();
Hey so a bit of an overview of the project i want to do. I want to show the user's teams.
When the user logged in and opened the viewteams page. He must show teams he joined/created. To do so i ve done the below processes...
my ViewTeamController
{
public function index()
{
$user=User::first();
$teams=Team::all();
$user->teams()->attach($teams);
return view('teams.viewteams',compact('teams'));
}
public function store()
{
}
}
my User model
public function teams(){
return $this->belongsToMany(Team::class,'team_user','teams_id','users_id');
}
my Team model
public function users(){
return $this->belongsToMany(User::class,'team_user','teams_id','users_id');
}
my migration of the pivot table
public function up()
{
Schema::create('team_user', function (Blueprint $table) {
$table->unsignedBigInteger('users_id');
$table->unsignedBigInteger('teams_id');
$table->index('users_id');
$table->index('teams_id');
$table->timestamps();
});
}
web.php routes
Route::get('/viewteams','ViewTeamController#index');
Route::post('/viewteams','ViewTeamController#store');
my viewteams.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header"><h2 style="text-align:center;">Your Teams</h2></div>
<div class="card-body">
#foreach ($teams as $team)
#foreach($team->users as $user)
{{$user->org_name}}
#endforeach
#endforeach
</div>
</div>
</div>
</div>
</div>
#endsection
my other controller for Creating a team
<?php
namespace App\Http\Controllers;
use App\Team;
use Illuminate\Http\Request;
class CreateTeamController extends Controller
{
public function index(Request $request)
{
return view('teams.createteams');
}
public function store(Request $request)
{
$team=Team::create($request->all());
return redirect()->route('home');
}
}
all my routes
Route::get('/login', function () {
return view('auth/login');
});
Auth::routes();
Route::get('/viewteams','ViewTeamController#index');
Route::post('/viewteams','ViewTeamController#store');
Route::get('/createteams','CreateTeamController#index');
Route::post('/createteams','CreateTeamController#store') ;
Route::get('/home', 'HomeController#index')->name('home');
To achieve currents users teams, first you should get authenticated user id using Auth facade.
After that you can load joined teams for user, using 'with' method. It loads teams relationships.
ViewTeamController
public function index()
{
$user = User::with('teams')->find(Auth::id());
return view('teams.viewteams',compact('user'))
}
viewteams.blade.php
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header"><h2 style="text-align:center;">Your Teams</h2></div>
<div class="card-body">
#foreach ($user->teams as $team)
{{ $team->name }}
#endforeach
</div>
</div>
</div>
</div>
</div>
#endsection
You will need to revisit and update the code which stores data to the users table and the teams user. The easiest way to store the data in a way which populates the pivot table is to use the sync() method as described at https://laravel.com/docs/master/eloquent-relationships#updating-many-to-many-relationships
I'm making some assumptions about names and relationships, buy you may have something like this:
$user = User::find(2);
$user->teams()->sync([4,5]);
In this case, you would put into the pivot table a record for user_id of 2 and team_id of 4, and a second record for a user_id of 2 and a team_id of 5.
If you want to share more code showing route definitions and controllers for how you are currently handling things, we can help with any more specific implementation questions.
I'm looking for solution to use dropzoneJs in laravel 5.5 while writing my products.
What I want to do is: upload my images and fill my product info then save all together just like WordPress/Joomla etc.
What do I have so far:
Images Table
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('image');
$table->integer('product_id')->nullable()->unsigned();
$table->timestamps();
});
Schema::table('images', function($table) {
$table->foreign('product_id')->references('id')->on('products');
});
}
My form in Products create.blade.php
<div class="row">
<div class="col-md-12">
{!! Form::open([ 'route' => [ 'dropzone.store' ], 'files' => true, 'enctype' => 'multipart/form-data', 'class' => 'dropzone', 'id' => 'image-upload' ]) !!}
{{ csrf_field() }}
<div>
<h4 style="text-align: center;color:#428bca;">Drop images in this area <span class="glyphicon glyphicon-hand-down"></span></h4>
<!-- Input code below Not working yet -->
<input type="text" name="product_id" value="" hidden>
</div>
{!! Form::close() !!}
</div>
</div>
My JavaScript code:
<!-- drozone -->
<script type="text/javascript">
Dropzone.options.imageUpload = {
maxFilesize: 5, //MB
acceptedFiles: ".jpeg,.jpg,.png,.gif"
};
</script>
My ImageController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Image;
use App\Product;
class ImageController extends Controller
{
public function dropzone()
{
return view('dropzone-view');
}
public function dropzoneStore(Request $request)
{
$image = $request->file('file');
$imageName = time().$image->getClientOriginalName();
$image->move(public_path('images'),$imageName);
return response()->json(['success'=>$imageName]);
}
}
And my routes:
Route::get('dropzone', 'ImageController#dropzone');
Route::post('dropzone/store', ['as'=>'dropzone.store','uses'=>'ImageController#dropzoneStore']);
Any Idea On That?