I'm new to laravel and i'm trying to add a new row in my database but it is not working.
The ultimate goal is to link it to my react native app so that every time a new user logs in, they get a unique token. For now just adding a new row with static data would be nice.
this is what I have in my routes: web.php:
Route::post('/posts/addnewdata', 'PostsController#create');
Route::get('/posts/printall', 'PostsController#index');
Route::get('/posts/{post}', 'PostsController#show');
and then in my controllers I have this:
<?php
namespace App\Http\Controllers;
use DB;
use App\Post;
class PostsController
{
public function index()
{
$allposts = Post::all();
$allposts->toJson();
return $allposts->toJson(JSON_PRETTY_PRINT);
}
public function show($slug)
{
$post = Post::where('title', $slug)->firstOrFail();
$post->toJson();
return $post->toJson(JSON_PRETTY_PRINT);
}
public function create()
{
$newData = array('id' => 6, 'title' => 'post-6', 'slug' => 'blog-6', 'body' => 'blog six in the database');
Post::create($newData);
}
}
when i type in the http://someurl/printall or the http://someurl/{some slug that is in my DB} it works, but the addnewdata gives a 404.
Related
I am trying to get exercise id to complete the table, how can I get the exercise ID, like I am getting it in Auth::user()->id
<?php
namespace App\Http\Controllers;
use App\Models\MyExercises;
use Illuminate\Http\Request;
use App\Models\Exercise;
use Illuminate\Support\Facades\Auth;
class MyExerciseController extends Controller
{
public function index()
{
$myexercises = MyExercises::paginate();
return view('exercises.myexercises', compact('myexercises'));
}
public function assign(Request $request)
{
$myexercises = MyExercises::create([
'description' =>$request->description,
'done' =>$request->done,
'user_id' => Auth::user()->id,
'exercises_id' =>(xxxxxx),
'place' =>$request->place,
'duration' =>$request->duration,
]);
return redirect()->route('myexercises.index');
I have tried doing it like this in the Controller, but right now I am a bit lost on how to proceed, thank you!
public function id()
{
$client = DB::table('My_exercises')
->where('id', '=', $request->get('id'))
->first();
}
PHP Version:7.2
Laravel Version:6.2
I am doing a simple project by laravel by article.
When I meet with redirect()->action, I am a little confused about that.
I want to pass a variable named id by redirect()->action but it does't work.
Error Message is Missing required parameters for [Route: blog/post.show] [URI: blog/post/{post}].
If I remove the variable name, only pass the variable value and it would work. I read the manual but still could not understand the reason. Could you help me explain the logic. Thank you. Below is the sample code.
Router.php
Route::group(['prefix' => 'blog',
'as' => 'blog/',
'namespace' => 'Blog'],
function(){
Route::resource('/post',"PostController");
});
PostController.php
Create new blog post ( wrong )
Couldn't understant why this does't work ? Variable name($id) is the same.
public function store(Request $request)
{
$post = new BlogPost;
$post->title = $title;
$post->content = $content;
$post->save();
return redirect()->action(
'Blog\PostController#show', ['id' => $post->id]
);
}
Create new blog post ( correct )
public function store(Request $request)
{
$post = new BlogPost;
$post->title = $title;
$post->content = $content;
$post->save();
return redirect()->action(
'Blog\PostController#show', [$post->id]
);
//Or 'Blog\PostController#show', $post->id
}
Show the new blog post
public function show($id)
{
$post = BlogPost::find($id);
if(! $post) {
abort(404);
}
$content = $post->content;
return view("blog.post", [
"title" => $post->title,
"content" => $content,
]);
}
Thank you
Here is code :
return redirect()->route('routename', ['id' => 1]);
You got the error message because you are using the Resource Route and it will automatic bind the Model with Route
For More Info please refer: https://laravel.com/docs/6.x/routing#route-model-binding
I encountered this error myself when trying to use a redirect()->action. Here's a simple example that will fail in just the same way.
class SimpleController extends Controller {
public function index() {
return redirect()->action([static::class, 'show'], ['id' => 7]);
}
public function show($id) {
// ... code goes here ...
}
}
And in the routes somewhere:
Route::resource('somethingsimpler', SimpleController);
The reason this fails is because default stub used by Route::resource for show is the same as the resource name. Have a read here: https://laravel.com/docs/9.x/controllers#actions-handled-by-resource-controller
Solution 1
We could change our original example to using 'somethingsimpler' instead of 'id'.
class SimpleController extends Controller {
public function index() {
return redirect()->action([static::class, 'show'], ['somethingsimpler' => 7]);
}
public function show($id) {
// ... code goes here ...
}
}
And in the routes somewhere:
Route::resource('somethingsimpler', SimpleController);
However, this seems to negate the whole purpose of using redirect()->action.
Solution 2
Reading further in the same document linked above, it seems you can set the resource name https://laravel.com/docs/9.x/controllers#restful-naming-resource-route-parameters.
class SimpleController extends Controller {
public function index() {
return redirect()->action([static::class, 'show'], ['id' => 7]);
}
public function show($id) {
// ... code goes here ...
}
}
And in the routes somewhere:
Route::resource('somethingsimpler', SimpleController)->parameters([
'somethingsimpler' => 'id'
]);
Solution 3 - Recommended
Reading the rest of the document, it becomes obvious that you can probably get away with not even naming the parameter.
class SimpleController extends Controller {
public function index() {
return redirect()->action([static::class, 'show'], [7]);
}
public function show($id) {
// ... code goes here ...
}
}
And in the routes somewhere:
Route::resource('somethingsimpler', SimpleController);
Having a bit of trouble understanding how to attach my foreign key to my child record when I insert it into my db. I have a casino class that can have many different locations within the casino(Restroom, Restaurant, Valet, Etc.). I am trying to create a new record in my db of the location and include the foreign key(casino_Id) which is the id of the casino table. I am not sure how I would be able to obtain that id unless I pass it in directly from the post by the route which I am doing in my show.blade.php file within my casino views.
<button class="btn btn-primary">Add Location</button>
Not entirely sure if this is a practical/safe way of passing in that info or how to obtain it from my create function. Currently I have it finding the first casino record it can find in the db to see how it inserts it which it does insert into the db but does not include the foreign key on insert.
web.php
//Location Routes
Route::get('/casino/{casino}/location/create', 'LocationController#create');
Route::post('/location', 'LocationController#store');
Route::get('/location/{location}', 'LocationController#show');
Route::get('/location/{location}/edit', 'LocationController#edit');
Route::patch('/location/{location}', 'LocationController#update');
casino.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Casino extends Model
{
public function locations() {
return $this->hasMany(Location::class)->orderBy('title', 'ASC');
}
}
location.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Location extends Model
{
protected $guarded = [];
protected $fillable = ['title'];
public function casino() {
return $this->belongsTo(Casino::class);
}
public function duties() {
return $this->hasMany(Duty::class)->orderBy('title', 'ASC');
}
}
create and store functions in my LocationController.php
public function create() {
return view('locations.create');
}
public function store(Request $request) {
$casino = Casino::find(1);
$request->validate([
'title' => 'required',
]);
$casino->location = new location([
'title' => $request->get('title'),
]);
$casino->location->save();
return redirect("/casino/1");
}
You can change your route from
Route::get('/casino/{casino}/location/create', 'LocationController#create');
Route::post('/location', 'LocationController#store');
to
Route::get('/casinos/{casino}/locations/create', 'LocationController#create');
Route::post('casinos/{casino}/location', 'LocationController#store');
Your create action
public function create(Casino $casino)
{
return view('locations.create', compact('casino'));
}
Your store action
public store(Request $request, Casino $casino)
{
$request->validate(['title' => 'required']);
$casino->location()->create($request->validated());
return redirect("/casino/{$casino->id}");
}
Route Model Binding
I want to validate the input fields before storing the data in database so i went through the laravel docs and followed these
php artisan make:request StoreLessons
in StoreLessons
public function rules()
{
return [
'title' => 'required|unique:lesson',
'body' => 'required',
];
}
in my controller
namespace App\Http\Controllers;
use Response;
use App\lesson;
use Illuminate\Http\Request;
use App\Acme\Transformers\LessonTransformer;
use Illuminate\Support\Facades\Input;
use App\Http\Requests\StoreLessons;
class LessonsController extends ApiController
{
protected $lessonTransformer;
function __construct(LessonTransformer $lessonTransformer)
{
$this->lessonTransformer = $lessonTransformer;
}
//fetch all and pass a metadata 'data'
public function index()
{
$lessons = Lesson::all();
return $this->respond([
'data' => $this->lessonTransformer->transformCollection($lessons->all())
]);
}
//add a new lesson to lessons table
public function store(StoreLessons $request)
{
Lesson::create($request->all());
//Lesson::create(input::all());
return $this->respondCreated('Lesson created successfully');
}
}
now i'm getting this error
QueryException in Connection.php line 770:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'laravel_api.lesson' doesn't exist (SQL: select count(*) as aggregate from `lesson` where `title` = the)
i don't know why it's looking for lesson table i have a lessons table
but the store() function works with default validation
//this works fine but i wan to do the validation
public function store()
{
if (! input::get('title') or ! input::get('body')) {
return $this->respondBadRequest();
}
Lesson::create(input::all());
return $this->respondCreated('Lesson created successfully');
}
Thank You
unique:table,column,except,idColumn
The unique syntax goes as above and the first parameter passed is the table name.
public function rules() {
return [ 'title' => 'required|unique:lesson', 'body' => 'required', ];
}
The unique rule here looks for a table lesson. Try changing that to lessons
Please write below line after related model class name like this.
class xyz extends Model
{
protected $table = 'lessons';
code---
}
Try this.
If a User has many posts, and a post belongs to user, it's simple to do:
$factory->define(App\Post::class, function ($faker) {
return [
'title' => $faker->title,
'content' => $faker->paragraph,
'user_id' => function () {
// Creates a User for every Post
return factory(App\User::class)->create()->id;
}
];
});
How do I accomplish the opposite? Instead, creating say 5 posts when a user is created and associating that post to the newly created user?
~Edit
I am using laravel 5.2, and I've declared my model relationships in my models, so I now have:
$user = factory(App\User::class)->create();
$posts = factory(App\Post::class, 3)->make();
$user->posts()->saveMany($posts);
// Great, now I have a User and 3 Posts associated with that user.
// However, now, I want let's say, 5 votes per post.
// I can't call $posts->votes(), so I iterate
foreach ($posts as $post) {
$votes = factory(App\Votes::class, 5)->make();
$post->votes()->saveMany($votes);
}
Then any other relation to votes, etc would just be nested in the foreach.
I would use Model Events for that. In your AppServiceProvider, add the events as below:
namespace App\Providers;
use App\User;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
User::created(function ($user) {
$posts = factory(App\Post::class, 3)->make();
$user->posts()->saveMany($posts);
});
Post::created(function ($post){
$votes = factory(App\Vote::class, 3)->make();
$post->votes()->saveMany($votes);
});
}
Now you do not have to worry about the automatic creation, also, this should not be part of the Controller logic anyways.
$factory->define(App\User::class, function ($faker) {
return [
'name' => $faker->name,
'email' => $faker->email
];
});
$factory->define(App\Post::class, function ($faker) {
return [
'title' => $faker->title,
'content' => $faker->paragraph
];
});
$user = factory(User::class)->create();
$post = factory(User::class)->create();
$user->posts()->associate($post);
Create 5 fakers in $posts
$posts = factory(App\Post::class, 3)->make();
$user->posts()->saveMany($posts);